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

sam*_*ami 8 python popen

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

test.py:

while True:
  print"hello"
Run Code Online (Sandbox Code Playgroud)

a.py :

import os  
os.popen('python test.py')
Run Code Online (Sandbox Code Playgroud)

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

atx*_*atx 17

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

你可以像这样使用它:

from subprocess import Popen, PIPE

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


ism*_*ail 12

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

from subprocess import Popen, PIPE

proc = Popen(["python","test.py"], stdout=PIPE)
output = proc.communicate()[0]
Run Code Online (Sandbox Code Playgroud)