2014-09-19 72 views
0

我有shell腳本,它在終端執行時輸出一些文本結果。閱讀shell腳本導致python

我能夠執行從Python腳本,shellscipt,但我不能存儲shell腳本導致成蟒蛇

我的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 
+1

如果你想讀在bash文件的最後一行,您可以用'尾-n 1 input.txt.responses' – 2014-09-19 08:11:47

回答

5

可以使用subprocess.check_output(),而不是subprocess.call()

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

它給出'OSError:[Errno 8]執行格式錯誤'錯誤 – user123 2014-09-19 09:10:30

+1

@ user123:或者(首選)添加行'#!/ usr/bin/env bash'到cherryP.sh的頂部,或者添加'shell = True'到'check_output()'。後者是潛在的安全風險,請參閱https://docs.python.org/2/library/subprocess.html#frequently-used-arguments – mhawke 2014-09-19 09:18:54

+0

嘗試它,一旦我執行「python cherryP.y」執行停止,什麼都不會發生 – user123 2014-09-19 09:51:23

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

+0

它給OSERROR:[錯誤8] Exec的格式錯誤錯誤 – user123 2014-09-19 09:11:58

+0

我加這個代碼,你能提出一些衝突嗎? – user123 2014-09-19 09:56:15

+1

您在我的環境中執行得很好的代碼,並打印文本文件的內容。您正在嘗試閱讀的文件的內容是什麼? – 2014-09-19 10:38:14