How to use the subprocess Popen.communicate() method?

青春壹個敷衍的年華 提交于 2020-12-12 04:47:16

问题


I'm trying to get the standard output of a bash command as a string in Python. Following Popen documentation, I've tried:

import subprocess

p = subprocess.Popen(["echo", "hello"])
stdoutdata, stderrdata = p.communicate()

print stdoutdata

Running this script yields the following output:

hello
None
[Finished in 0.0s]

So although the output is getting printed by Python, the stdoutdata variable is None, and not "hello" as I would like. How can I make it so?


回答1:


You're not providing any stdout to the Popen constructor, the default functionality simply writes the output to parent's stdout handle. Hence you're seeing it being printed in your shell.

Quoting from Popen's docs:

With the default settings of None, no redirection will occur; the child’s file handles will be inherited from the parent.


To populate stdout in resulting tuple use subprocess.PIPE as stdout.

Quoting from docs:

To get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

>>> import subprocess
>>> p = subprocess.Popen(["echo", "hello"], stdout=subprocess.PIPE)
>>> p.communicate()
('hello\n', None)



回答2:


You need to pass stdout, stderr flags to Popen constructor.
Per default they are set to None, resulting in Popen is not capturing them.

cmd = subprocess.Popen(["echo", "hello"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = cmd.communicate()
# retCode = cmd.returncode
# retCode != 0, indicates an error occured in execution.
print (out)
>>> b'hello\n'



回答3:


It seems like the subprocess.check_output method is what I need:

import subprocess
output = subprocess.check_output(["echo", "hello"])

The output is now 'hello\n' (including a newline character) as I would expect.



来源:https://stackoverflow.com/questions/44155140/how-to-use-the-subprocess-popen-communicate-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!