【问题标题】:subprocess.Popen process stdout returning empty?subprocess.Popen 进程标准输出返回空?
【发布时间】:2016-10-13 17:44:52
【问题描述】:

我有这个 python 代码

input()
print('spam')

另存为ex1.py

在交互式外壳中

>>>from subprocess import Popen ,PIPE
>>>a=Popen(['python.exe','ex1.py'],stdout=PIPE,stdin=PIPE)

>>> a.communicate()

(b'', None)

>>>

为什么不打印spam

【问题讨论】:

标签: python python-3.x subprocess


【解决方案1】:

输入需要一整行,但您的输入为空。所以只有一个异常写入stderr 而没有写入stdout。至少提供一个换行符作为输入:

>>> a = Popen(['python3', 'ex1.py'], stdout=PIPE, stdin=PIPE)
>>> a.communicate(b'\n')
(b'spam\n', None)
>>> 

【讨论】:

  • 谢谢,我刚刚添加了stderr=PIPE,然后运行程序,发现错误为(b'', b'Traceback (most recent call last):\r\n File "receive_from_sub.py", line 5, in <module>\r\n input()\r\nEOFError: EOF when reading a line\r\n')
【解决方案2】:

你要找的是subprocess.check_output

【讨论】:

  • 你能解释一下你的答案是如何解决上述问题的吗?
  • 嗨 Rakesh,你看到我在 cmets 中链接的问题了吗? store the output of subprocess.popen call in a string这个函数专门用于获取另一个进程的输出。
  • 虽然您的答案可能是正确的,但最好解释一下为什么它是正确的。这对 OP 进行了教育,帮助他们了解如何在未来避免该问题。
【解决方案3】:

您缺少stderr 管道:

from subprocess import Popen ,PIPE

proc = Popen(['python.exe','ex1.py'], stdout=PIPE, stderr=PIPE)
out, err = proc.communicate()
print(out, err)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 2017-03-24
    • 2010-12-21
    • 2021-09-03
    相关资源
    最近更新 更多