2013-05-31 176 views
0

我需要從python調用shellscript。 問題在於,shellscript會一直提出幾個問題,直到完成。我不能找到使用subprocess的方法! (使用pexpect似乎有點過度殺,因爲我只需要啓動它併發送幾個YES)從Python子進程執行shell腳本

請不要建議需要修改shell腳本的方法!

+0

如果可能,那麼你應該創建另一個shell腳本(2)解答了你的腳本(1)使用eof或讀取。然後用python subprocess.popen執行腳本, –

+0

'os.system('yes | sed s/y/yes/| ./myshell.sh')' – Elazar

回答

3

使用subprocess庫,你可以告訴你要管理的過程是這樣的標準輸入Popen類:

import subprocess 
shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE) 

現在shellscript.stdin是一個類似文件的對象上,你可以調用write

shellscript.stdin.write("yes\n") 
shellscript.stdin.close() 
returncode = shellscript.wait() # blocks until shellscript is done 

您也可以通過設置stdout=subprocess.PIPEstderr=subprocess.PIPE得到一個進程的標準輸出和標準錯誤,但您不應將PIPEs用於標準輸入和標準輸出,因爲可能導致死鎖。 (見documentation)。如果您需要在管道和管出來,使用communicate方法,而不是類文件對象:

shellscript = subprocess.Popen(["shellscript.sh"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
stdout, stderr = shellscript.communicate("yes\n") # blocks until shellscript is done 
returncode = shellscript.returncode 
+0

stdout,應該在第二個Popen調用中設置stderr,否則'.communicate ()'返回'None's(不重定向) – jfs

+0

啊,對 - 這就是我的意思,但我會編輯答案更明確。 (或者,也許你已經這樣做了?無論如何,現在看起來對我有用。) –

+0

也可以'從子流程導入Popen,PIPE'來避免'subprocess.'前綴的可讀性 – jfs