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

时间:2013-06-21 14:53:14

标签: python linux bash shell unix

我有一个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的模块”。我想我的verison(Python 2.3.4)已经很老了。在这种情况下是否可以替代可以应用的子进程?

2 个答案:

答案 0 :(得分:7)

使用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

答案 1 :(得分:2)

使用 Subprocess.check_output 而不是 Subprocess.call

Subprocess.call 返回该脚本的返回码。
Subprocess.check_output 返回脚本输出的字节流。

Subprocess.check_output on python 3.3 doc site

相关问题