简体   繁体   English

在Python中将PIPE的输出重定向到FILE

[英]Redirecting Output of PIPE to a FILE in python

Following code is to redirect the output of the Pipe to a file "CONTENT" and it has some content, I want to overwrite it with output of "sort CONTENT1 | uniq ".... But I'm not able overwrite it and also i don't know weather following code is redirecting to CONTENT(ie correct or not) or not. 以下代码是将Pipe的输出重定向到文件“ CONTENT”,并且其中包含一些内容,我想用“ sort CONTENT1 | uniq”的输出覆盖它。...但是我无法覆盖它,并且我不知道天气以下代码是否重定向到CONTENT(即正确与否)。 Please help me out.... 请帮帮我。

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__

Here is how you can catch the output of the first process and pass it to the second, which will then write its output to the file: 这是捕获第一个进程的输出并将其传递给第二个进程的方法,该进程随后将其输出写入文件:

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

You should not tinker with sys.stdout at all. 您根本不应该修改sys.stdout Note that you need one call to the method communicate for each process. 请注意,您需要为每个过程调用一次方法communicate Note also that communicate() will buffer all output of p1 before it is passed to p2 . 还要注意, communicate()将在将p1所有输出传递给p2之前对其进行缓冲。

Here is how you can pass the output of p1 line-by-line to 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()

The cleanest way to do the pipe would be the following: 做管道的最干净方法是:

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()

Alternatively, of course, you could just use the facilities of the shell, which is just made for these tasks: 当然,您也可以只使用Shell的功能,这些功能正是为这些任务而设计的:

import subprocess
with open('CONTENT','w') as f1:
    p = subprocess.Popen("sort CONTENT1 | uniq", shell=True,
                         stdout=f1)

Reference: http://docs.python.org/2/library/subprocess.html 参考: http : //docs.python.org/2/library/subprocess.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM