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

9 投票
3 回答
59524 浏览
提问于 2025-04-16 09:04

我想用 popen 来处理我文件的输出,应该怎么做呢?

test.py:

while True:
  print"hello"

a.py:

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

我想用 os.popen 来处理输出。那我该怎么做呢?

3 个回答

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改成这样,方便大家理解发生了什么:

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

12

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

from subprocess import Popen, PIPE

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

首先,os.popen()这个方法已经不推荐使用了,建议你用subprocess模块来代替。

你可以这样使用它:

from subprocess import Popen, PIPE

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

撰写回答