bash 如何从python脚本中的shell脚本返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17238263/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to return a value from a shell script in a python script
提问by user2475677
I have a python script which requires a value from a shell script.
我有一个需要来自 shell 脚本的值的 python 脚本。
Following is the shell script (a.sh):
以下是 shell 脚本 (a.sh):
#!/bin/bash
return_value(){
value=$(///some unix command)
echo "$value"
}
return_value
Following is the python script:
以下是python脚本:
Import subprocess
answer = Subprocess.call([‘./a.sh'])
print("the answer is %s % answer")
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??
但它不起作用。错误是“ImportError:No module named subprocess”。我想我的版本(Python 2.3.4)已经很旧了。在这种情况下,是否可以替代子流程?
回答by Ashwini Chaudhary
Use subprocess.check_output:
使用subprocess.check_output:
import subprocess
answer = subprocess.check_output(['./a.sh'])
print("the answer is {}".format(answer))
help on subprocess.check_output:
帮助subprocess.check_output:
>>> print subprocess.check_output.__doc__
Run command with arguments and return its output as a byte string.
Demo:
演示:
>>> 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:
a.sh:
#!/bin/bash
STR="Hello World!"
echo $STR
回答by Krab
use Subprocess.check_outputinstead of Subprocess.call.
使用Subprocess.check_output而不是 Subprocess.call。
Subprocess.callreturns return code of that script.
Subprocess.check_outputreturns byte stream of script output.
Subprocess.call返回该脚本的返回码。
Subprocess.check_output返回脚本输出的字节流。

