如何使用子进程 Popen.communicate() 方法?

编程入门 行业动态 更新时间:2024-10-15 08:23:23
本文介绍了如何使用子进程 Popenmunicate() 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将 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 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?

解决方案

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() 方法?

本文发布于:2023-08-05 02:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1301651.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   进程   方法   Popen   communicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!