2012-03-03 88 views
9

我讀的每個線程我在計算器上發現使用subprocess從Python中調用shell命令,但我找不到適用於我的情況如下答案子:殼牌管道可以用Python

我想這樣做來自Python的以下內容:

  1. 運行shell命令command_1。收集輸出在可變result_1

  2. 殼管result_1command_2並收集result_2的輸出。換句話說,使用我運行當在步驟command_1之前

  3. 照此管道result_1到第三命令command_3result_3收集結果而獲得的結果運行command_1 | command_2

到目前爲止,我曾嘗試:

p = subprocess.Popen(command_1, stdout=subprocess.PIPE, shell=True) 

result_1 = p.stdout.read(); 

p = subprocess.Popen("echo " + result_1 + ' | ' + 
command_2, stdout=subprocess.PIPE, shell=True) 

result_2 = p.stdout.read(); 

的原因似乎是"echo " + result_1不模擬獲得命令的輸出管道的過程。

這是所有可能的使用子進程?如果是這樣,怎麼樣?

+2

請參閱[本文檔中的示例](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline)以獲取正確的方法。 – 2012-03-03 01:00:34

+1

謝謝@SvenMarnach,那還能讓我收集Python變量中第一條命令的輸出嗎? – 2012-03-03 01:03:52

回答

8

你可以這樣做:

pipe = Popen(command_2, shell=True, stdin=PIPE, stdout=PIPE) 
pipe.stdin.write(result_1) 
pipe.communicate() 

,而不是與管道線路。

+0

這看起來不錯。如果我想將'result_1' *再次*傳遞給另一個命令,上述更改將如何? – 2012-03-03 01:46:46

+1

那時''result_1'是一個字符串。你應該可以用新命令重複相同的3行。 – 2012-03-04 06:21:58