读取shell脚本导致python

时间:2014-09-19 07:58:49

标签: python bash shell

我有shell脚本,在执行时在终端上输出一些文本结果。

我能够从python脚本执行那个shellscipt,但我无法将shell脚本结果存储到python中

我的python脚本:

import subprocess
#result = subprocess.call(['/root/Desktop/karim/software/cherrypicker1.01/cherryP.sh'],shell = True)   This yields result 0
subprocess.call(['/root/Desktop/karim/software/cherrypicker1.01/cherryP.sh'],shell = True)
print "REsult is  : "
print result

cherryP.sh

./cherrypicker.sh input.txt
#for line in $(cat input.txt.responses); do echo "$line" ; done
DONE=false
until $DONE
do
  read line || DONE=true
  echo $line   # this will echo the result which I want to use in python script
done < input.txt.responses

我做错了什么,或者其他合理的解决方案是什么?

更新了cherryP.py

import subprocess
result = subprocess.check_output(['/root/Desktop/karim/software/cherrypicker1.01/cherryP.sh'], shell = True)
print result

2 个答案:

答案 0 :(得分:5)

您可以使用subprocess.check_output()代替subprocess.call()

import subprocess
result = subprocess.check_output(['/root/Desktop/karim/software/cherrypicker1.01/cherryP.sh'])
print result

答案 1 :(得分:2)

为了在变量中获取外部程序的结果,您需要使用subprocess.check_output函数:

subprocess.check_output(['/root/Desktop/karim/software/cherrypicker1.01/cherryP.sh'])

您正在使用的subprocess.call函数返回它执行的脚本的退出代码。退出代码0,意味着程序完成执行而没有错误。

您可以在此处详细了解退出状态: http://tldp.org/LDP/abs/html/exit-status.html