2013-06-21 61 views
1

我有一个python脚本,它需要来自shell脚本的值。如何从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") 

但它不是working.The错误是“导入错误:没有模块名为子”。我想我的verison(Python 2.3.4)很旧。在这种情况下是否有可用于子过程的替代?

回答

5

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

感谢ashwini的答案。python脚本内部的声明实际上不是打印语句,而是cvs命令。为了提问,我简化了它。那么在这种情况下,我们可以使用{}来插入答案变量,或者我们需要使用%s? – user2475677

+0

@ user2475677 [str.format](http://docs.python.org/2/library/string.html#formatspec)被称为新风格的字符串格式,如果您只使用字符串格式,那么这两个选项都可以。 –

+0

非常感谢ashwini,但我刚刚意识到,我的Python版本(2.3.4)非常老!它没有“子进程” – user2475677