2014-04-13 29 views
0

如果以前有人問過這個問題,我抱歉抱歉,我沒有找到答案。如何使用popen將stdout管道傳輸到另一個程序?

我有系統的順序調用腳本我寫品牌,其中之一是以下形式:

cat file | /some/program o > output.txt 

從本質上說,郊遊文件到標準輸出,其通過管道輸送到一些程序,然後運行它並將輸出放到其他文件中。在這種情況下,/ some/program的使用非常不靈活,我必須在其中添加一個文件並使用參數o> some_out_file才能使用它。

將該行的shlex.split()傳遞給popen()的args只是打印文件,/ some/program的二進制文件和output.txt(如果存在的話),這顯然不是我正在尋找的內容對於。

我是相當新的使用這部分的python一般很抱歉,如果答案是顯而易見的,如果有其他方式使這個系統調用,而不是嘗試使用subprocess.popen()或類似的我對此也敞開心扉,任何幫助表示感謝!

另外,我可以只爲這個調用os.system(...),但爲了一致性的緣故與腳本的其餘部分,我寧願不使用在這種情況下的特定異常。

回答

0

這是你在找什麼?

Popen.communicate

與互動的過程:將數據發送至標準輸入。從stdout和stderr中讀取數據,直到達到文件結尾。等待進程終止。可選的輸入參數應該是要發送到子進程的字符串,如果沒有數據應該發送給子進程,則爲None。

這類似於調用cat file | head -n 10 > out.txt

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
import subprocess 

program="head" 
args=["-n", "10"] 
popen_args = [program] + args #["head", "-n", "10"] 

p = subprocess.Popen(popen_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
# sample stdin 
stdin = "\n".join(["line %s" % x for x in xrange(0, 100)]) 
out, err = p.communicate(stdin) 

# save to file 
with open('out.txt', 'w') as f: f.write(out) 
+0

你可以[通過文件直接POPEN(http://stackoverflow.com/a/23050802/4279) – jfs

0

在Python模擬< file /some/program o > output.txt shell命令:

from subprocess import check_call 

with open('file', 'rb', 0) as file, open('output.txt', 'wb', 0) as output_file: 
    check_call(['/some/program', 'o'], stdin=file, stdout=output_file) 

要回答標題中的問題,你可以使用"Replacing shell pipeline" example from the docs

from subprocess import Popen, PIPE 

# cat file | /some/program o > output.txt 
p1 = Popen(["cat", "file"], stdout=PIPE) 
with open('output.txt', 'wb', 0) as output_file: 
    p2 = Popen(["/some/program", "o"], stdin=p1.stdout, stdout=output_file) 
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits. 
p1.wait() 
p2.wait() 

如果shell命令來自受信任的輸入,你可以使用shell=True創建一個管道:

check_call("/bin/a b c | /bin/d 'e f'", shell=True) 
相關問題