Python - 如何使用popen管道输出?

9

我想使用popen将文件的输出进行管道传输,应该如何操作?

test.py:

while True:
  print"hello"

a.py :

import os  
os.popen('python test.py')

我想使用os.popen来进行输出管道,我该如何做到同样的效果呢?
3个回答

17

首先,os.popen()已弃用,请改用subprocess模块。

你可以像这样使用:

from subprocess import Popen, PIPE

output = Popen(['command-to-run', 'some-argument'], stdout=PIPE)
print output.stdout.read()

1
示例展示了这一点。您应该使用:Popen(['python','test.py'],stdout = PIPE) - atx
1
根据subprocess文档此处和其他答案,应该使用proc.communicate()[0]而不是stdout.read()来避免死锁。 - storm_m2138

12

使用subprocess模块,这里有一个例子:

from subprocess import Popen, PIPE

proc = Popen(["python","test.py"], stdout=PIPE)
output = proc.communicate()[0]

1
它将一直挂起,直到发生MemoryError。如果输出是无限的(如test.py情况),则不应使用.communicate()。而是直接使用proc.stdout逐步读取,参见Python:从subprocess.communicate()读取流式输入 - jfs

4

这将仅输出第一行结果:

a.py:

import os
pipe = os.popen('python test.py')
a = pipe.readline()
print a

...并且这将打印它们所有

import os
pipe = os.popen('python test.py')
while True:
    a = pipe.readline()
    print a

我已经将test.py更改为以下内容,以便更容易看到其中的操作:

(我将test.py更改为以下内容,以便更容易看到其中的操作:

#!/usr/bin/python
x = 0
while True:
    x = x + 1
    print "hello",x

)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接