【发布时间】:2010-12-27 07:39:09
【问题描述】:
我想使用popen 输出我的文件的pipe,我该怎么做?
test.py:
while True:
print"hello"
a.py:
import os
os.popen('python test.py')
我想使用os.popen 管道输出。
我该怎么做?
【问题讨论】:
我想使用popen 输出我的文件的pipe,我该怎么做?
test.py:
while True:
print"hello"
a.py:
import os
os.popen('python test.py')
我想使用os.popen 管道输出。
我该怎么做?
【问题讨论】:
这将只打印输出的第一行:
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
)
【讨论】:
首先,不推荐使用 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: read streaming input from subprocess.communicate()