我正在尝试将 bash 命令的标准输出作为 Python 中的字符串获取.按照 Popen 文档,我尝试过:
导入子流程p = subprocess.Popen(["echo", "hello"])标准输出数据,标准错误数据 = pmunicate()打印标准输出数据运行此脚本会产生以下输出:
你好没有任何【0.0s完成】因此,尽管输出是由 Python 打印的,stdoutdata 变量是 None,而不是我想要的 "hello".我怎样才能做到这一点?
解决方案您没有向 Popen 构造函数提供任何标准输出,默认功能只是将输出写入父级的标准输出句柄.因此,您会看到它被打印在您的外壳中.
引自 Popen 的文档:
默认设置None,不会发生重定向;子级的文件句柄将从父级继承.
要在结果元组中填充标准输出,请使用 subprocess.PIPE 作为标准输出.
引自 docs:
要在结果元组中获得除 None 以外的任何内容,您需要给出stdout=PIPE 和/或 stderr=PIPE 也是.
>>>导入子流程>>>p = subprocess.Popen(["echo", "hello"], stdout=subprocess.PIPE)>>>pmunicate()('你好\n', 无)
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 = pmunicate() print stdoutdataRunning 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?
解决方案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) >>> pmunicate() ('hello\n', None)
更多推荐
如何使用子进程 Popen.communicate() 方法?
发布评论