python - 如何使用popen管道输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4537259/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python - how to pipe the output using popen?
提问by sami
I want to pipeoutput of my file using popen, how can I do that?
我想使用pipe输出我的文件popen,我该怎么做?
test.py:
测试.py:
while True:
print"hello"
a.py:
一个.py:
import os
os.popen('python test.py')
I want to pipe the output using os.popen.
how can i do the same?
我想使用管道输出os.popen。我该怎么做?
回答by atx
First of all, os.popen() is deprecated, use the subprocess module instead.
首先, os.popen() 已弃用,请改用 subprocess 模块。
You can use it like this:
你可以这样使用它:
from subprocess import Popen, PIPE
output = Popen(['command-to-run', 'some-argument'], stdout=PIPE)
print output.stdout.read()
回答by ismail
Use the subprocessmodule, here is an example:
使用subprocess模块,这里是一个例子:
from subprocess import Popen, PIPE
proc = Popen(["python","test.py"], stdout=PIPE)
output = proc.communicate()[0]
回答by david van brink
This will print just the first line of output:
这将只打印第一行输出:
a.py:
一个.py:
import os
pipe = os.popen('python test.py')
a = pipe.readline()
print a
...and this will print all of them
...这将打印所有这些
import os
pipe = os.popen('python test.py')
while True:
a = pipe.readline()
print a
(I changed test.py to this, to make it easier to see what's going on:
(我将 test.py 更改为这个,以便更容易查看发生了什么:
#!/usr/bin/python
x = 0
while True:
x = x + 1
print "hello",x
)
)

