以下是如何捕获第一个进程的输出并将其传递给第二个进程,然后第二个进程会将其输出写入文件:
import subprocess
with open('CONTENT','w') as f1:
p1 = subprocess.Popen(["sort", "CONTENT1"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["uniq"], stdin=subprocess.PIPE, stdout=f1)
p1_out = p1.communicate()[0] # catch output
p2.communicate(p1_out) # pass input
你根本不应该修补sys.stdout
。请注意,您需要communicate
为每个进程调用一次方法。另请注意,这
communicate()
将p1
在传递给
p2
.
以下是如何将p1
逐行的输出传递给p2
:
import subprocess
with open('CONTENT','w') as f1:
p1 = subprocess.Popen(["sort", "CONTENT1"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["uniq"], stdin=subprocess.PIPE, stdout=f1)
out_line = p1.stdout.readline()
while out_line:
p2.stdin.write(out_line)
out_line = p1.stdout.readline()
做管道的最干净的方法如下:
import subprocess
with open('CONTENT','w') as f1:
p1 = subprocess.Popen(["sort", "CONTENT1"], stdout=subprocess.PIPE)
p2 = subprocess.Popen(["uniq"], stdin=p1.stdout, stdout=f1)
p1.stdout.close()
或者,当然,您可以只使用 shell 的功能,它专为这些任务而设计:
import subprocess
with open('CONTENT','w') as f1:
p = subprocess.Popen("sort CONTENT1 | uniq", shell=True,
stdout=f1)
参考:http ://docs.python.org/2/library/subprocess.html