2013-05-21 63 views
1

在我的Python代碼,我有在python執行shell命令文件作爲標準輸入

executable_filepath = '/home/user/executable' 
input_filepath = '/home/user/file.in' 

我要分析的輸出我會在外殼得到命令

/home/user/executable </home/user/file.in 

我試過

command = executable_filepath + ' <' + input_filepath 
p = subprocess.Popen([command], stdout=subprocess.PIPE) 
p.wait() 
output = p.stdout.read() 

但它不起作用。我現在能想到的唯一解決方案是創建另一個管道,並通過它複製輸入文件,但必須有一個簡單的方法。

回答

4
from subprocess import check_output 

with open("/home/user/file.in", "rb") as file: 
    output = check_output(["/home/user/executable"], stdin=file) 
0

您需要在致電Popen時指定shell=True。默認情況下,[command]直接傳遞給exec系列中的系統調用,該系統不理解shell重定向操作符。

或者,你可以讓Popen過程連接到文件:

with open(input_filepath, 'r') as input_fh: 
    p = subprocess.Popen([executable_filepath], stdout=subprocess.PIPE, stdin=input_fh) 
    p.wait() 
    output=p.stdout.read() 
+1

調用'.wait()''之前.stdout.read()'會導致如果子進程死鎖產生足夠的輸出。 – jfs