【问题标题】:Displaying console output from subprocess [duplicate]显示子进程的控制台输出[重复]
【发布时间】:2014-06-30 11:06:53
【问题描述】:

我想知道,如何获取 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()

【问题讨论】:

  • 不要使用call,而是使用check_output

标签: python subprocess stdout


【解决方案1】:

使用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."

【讨论】:

  • 谢谢!我的代码还有其他问题,当时我还没有看到。 subprocess.Popen(["cat", target], stdout=subprocess.PIPE).communicate()[0] 将返回空字符串,因为文件没有关闭。
  • 好的,是的,只需在 Popen 之前添加 close... 即可编辑 :) 感谢您的关注!
猜你喜欢
  • 2018-10-18
  • 2014-03-13
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 2018-04-08
  • 2015-11-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多