【问题标题】:Python Subprocess Empty OutputPython 子进程空输出
【发布时间】:2018-01-10 09:16:21
【问题描述】:

我有这个代码:

pprocess = subprocess.Popen('PROGRAM', stdout=subprocess.PIPE)

while True:
    output = pprocess.stdout.readline()
    print 'output = ', output

但输出不是使用 python 代码打印的,而是在控制台上打印,而且它似乎是直接从进程中打印出来的。

有人遇到过这个问题吗?

【问题讨论】:

  • 在终端中调用 PROGRAM 时返回什么?
  • 它在终端上正确打印输出
  • 您需要将popen 也移动到while 循环中。
  • 为什么?它会导致每次打开popen

标签: python process subprocess


【解决方案1】:

但是输出不是使用 python 代码打印的,而是在控制台上打印的

似乎输出打印在 STDERR 流上,而不是 STDOUT 流上;您只是在捕获 STDOUT。

所以,也使用stderr 流:

pprocess = subprocess.Popen('PROGRAM', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Checking just the STDERR here
for line in pprocess.stderr:
    print(line)

附带说明,与其在while 循环中使用readline(),不如迭代Popen.stdout/Popen.stderr 提供的类文件对象,它们是迭代器。

【讨论】:

  • pprocess.stderr 中的“for 行:”行似乎被阻塞,流在那里停止
  • @JayR.W 从终端运行 program 2>/dev/null 。你有任何输出吗? (这是为了确认输出实际上正在写入 STDERR)
  • 正在写入的输出与我从这行代码收到的输出不同:“ print = self.sip_process.stderr.readline()”
【解决方案2】:

一旦您通过执行stdout.readline 读取stdout stream,它就会变为空。您要么必须将 Popen 调用移动到 while 循环中,要么更改您的逻辑:

while True:
    pprocess = subprocess.Popen('PROGRAM', stdout=subprocess.PIPE)
    output = pprocess.stdout.readline()
    print 'output = ', output

【讨论】:

    猜你喜欢
    • 2011-08-29
    • 2018-05-28
    • 2019-05-19
    • 2016-07-21
    • 2016-11-19
    • 2018-10-04
    • 2012-05-11
    • 2011-09-08
    • 2021-03-25
    相关资源
    最近更新 更多