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

时间:2010-12-27 07:39:10

标签: python popen

我想使用pipe popen输出我的文件,我该怎么做?

test.py

while True:
  print"hello"

a.py

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

我想使用os.popen来管道输出。 我怎么能这样做?

3 个答案:

答案 0 :(得分:17)

首先,不推荐使用os.popen(),而是使用子进程模块。

你可以像这样使用它:

from subprocess import Popen, PIPE

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

答案 1 :(得分:12)

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

from subprocess import Popen, PIPE

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

答案 2 :(得分:3)

这将只打印第一行输出:

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