显示子进程的控制台输出

时间:2014-05-12 22:31:24

标签: python subprocess stdout

我想知道,如何在Python脚本中调用子进程的输出?

from sys import argv
from os.path import exists
from subprocess import call

script, source, target = argv

print "Copying from %s to %s" % (source, target)

indata = open(source).read()

if exists(target):
    out_file = open(target, 'w')
    out_file.write(indata)
    call(["cat", target]) #how can I get text printed on console by cat?
    print "OK."
    out_file.close()

1 个答案:

答案 0 :(得分:3)

使用subprocess.Popen

>>> import subprocess
>>> var = subprocess.Popen(['echo', 'hi'], stdout=subprocess.PIPE)
>>> print var.communicate()[0]
hi

>>> 

myfile.txt

Hello there,

This is a test with python

Regards,
Me.

运行:

>>> import subprocess
>>> var = subprocess.Popen(['cat', 'myfile.txt'], stdout=subprocess.PIPE)
>>> print var.communicate()[0]
Hello there,

This is a test with python

Regards,
Me.

>>> 

另外,你有一点虫子。您正在检查目标是否存在,但您可能想要检查源是否存在。

以下是您编辑的代码:

from sys import argv
from os.path import exists
import subprocess

script, source, target = argv

print "Copying from %s to %s" % (source, target)

indata = open(source).read()

if exists(source):
    out_file = open(target, 'w')
    out_file.write(indata)
    out_file.close()
    var = subprocess.Popen(["cat", target], stdout=subprocess.PIPE) #how can I get text printed on console by cat?
    out = var.communicate()[0]
    print out
    print "OK."