我想使用popen
将文件的输出进行管道传输,应该如何操作?
test.py:
while True:
print"hello"
a.py :
import os
os.popen('python test.py')
我想使用
os.popen
来进行输出管道,我该如何做到同样的效果呢?首先,os.popen()已弃用,请改用subprocess模块。
你可以像这样使用:
from subprocess import Popen, PIPE
output = Popen(['command-to-run', 'some-argument'], stdout=PIPE)
print output.stdout.read()
使用subprocess
模块,这里有一个例子:
from subprocess import Popen, PIPE
proc = Popen(["python","test.py"], stdout=PIPE)
output = proc.communicate()[0]
test.py
情况),则不应使用.communicate()
。而是直接使用proc.stdout
逐步读取,参见Python:从subprocess.communicate()读取流式输入。 - jfs这将仅输出第一行结果:
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更改为以下内容,以便更容易看到其中的操作:
#!/usr/bin/python
x = 0
while True:
x = x + 1
print "hello",x
)