我有一个 python 脚本,它需要一个来自 shell 脚本的值。
以下是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:没有名为 subprocess 的模块”。我想我的版本 (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 - 如何从 python 脚本中的 shell 脚本返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17238263/