如何从shell脚本在Python脚本返回一个值
问题描述:
我有需要从shell脚本值的python脚本。
I have a python script which requires a value from a shell script.
以下是shell脚本(a.sh):
Following is the shell script (a.sh):
#!/bin/bash
return_value(){
value=$(///some unix command)
echo "$value"
}
return_value
以下是python脚本:
Following is the python script:
Import subprocess
answer = Subprocess.call([‘./a.sh’])
print("the answer is %s % answer")
但它不是working.The错误是导入错误:没有模块名为子。我想我的verison(Python的2.3.4)是pretty岁。有可在这种情况下,??
But its not working.The error is "ImportError : No module named subprocess ". I guess my verison (Python 2.3.4) is pretty old. Is there any substitute for subprocess that can be applied in this case??
答
使用 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