0

以下代码是将管道的输出重定向到文件“CONTENT”并且它有一些内容,我想用“sort CONTENT1 | uniq”的输出覆盖它......但我无法覆盖它而且我不知道天气下面的代码是否重定向到内容(即正确与否)。请帮帮我....

f1=open('CONTENT','w')      
sys.stdout=f1  
p1 = subprocess.Popen(["sort", "CONTENT1"], stdout=subprocess.PIPE)   
p2 = subprocess.Popen(["uniq"], stdin=p1.stdout, stdout=subprocess.PIPE)  
p1.stdout.close()  
p2.communicate()   
sys.stdout=sys.__stdout__
4

1 回答 1

1

以下是如何捕获第一个进程的输出并将其传递给第二个进程,然后第二个进程会将其输出写入文件:

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

于 2013-09-26T07:12:46.207 回答