如何从python脚本中的shell脚本返回值

我有一个python脚本,它需要shell脚本中的值.以下是外壳程序脚本(a.sh):#!/bin/bashreturn_value(){value=$(///some unix command)echo $value}return_value以下是python脚本:Import subprocessanswer = Subp...

我有一个python脚本,它需要shell脚本中的值.

以下是外壳程序脚本(a.sh):

#!/bin/bash
return_value(){
  value=$(///some unix command)
  echo "$value"
}

return_value

以下是python脚本:

Import subprocess
answer = Subprocess.call([‘./a.sh’])
print("the answer is %s % answer")  

但是它不起作用.错误是“ ImportError:没有名为子进程的模块”.我猜我的版本(Python 2.3.4)很老了.在这种情况下,是否可以替代子流程?

解决方法:

使用subprocess.check_output:

import subprocess
answer = subprocess.check_output(['./a.sh'])
print("the answer is {}".format(answer))

有关subprocess.check_output的帮助:

>>> print subprocess.check_output.__doc__
Run command with arguments and return its output as a byte string.

演示:

>>> import subprocess
>>> answer = subprocess.check_output(['./a.sh'])
>>> answer
'Hello World!\n'
>>> print("the answer is {}".format(answer))
the answer is Hello World!

a.sh:

#!/bin/bash
STR="Hello World!"
echo $STR

本文标题为:如何从python脚本中的shell脚本返回值

基础教程推荐