Python - 如何使用管道执行 shell 命令,但没有“shell=True"? [英] Python - how to execute shell commands with pipe, but without 'shell=True'?

查看:58
本文介绍了Python - 如何使用管道执行 shell 命令,但没有“shell=True"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个案例想在 Python 中执行以下 shell 命令并获取输出,

echo This_is_a_testing |grep -c 测试

我可以用这个python代码在python中执行上面的shell命令,

<预><代码>>>>导入子流程>>>subprocess.check_output("echo This_is_a_testing | grep -c test", shell=True)'1\n'

然而,因为我不想使用shell=True"选项,我尝试了以下python代码,

<预><代码>>>>导入子流程>>>p1 = subprocess.Popen([echo", This_is_a_testing"], stdout=subprocess.PIPE)>>>p2 = subprocess.Popen([grep", -c", test"], stdin=p1.stdout)>>>p1.stdout.close()>>>p2.communicate()(无,无)

我想知道为什么输出是None"?正如我在网页中提到的描述:http://docs.python.org/library/subprocess.html#subprocess.PIPE

我是否遗漏了代码中的某些要点?任何建议/想法?提前致谢.

解决方案

来自手册:

<块引用>

要在结果元组中获得 None 以外的任何内容,您需要给出stdout=PIPE 和/或 stderr=PIPE

p2 = subprocess.Popen(["grep", "-c", "test"], stdin=p1.stdout, stdout=subprocess.PIPE)

I have a case to want to execute the following shell command in Python and get the output,

echo This_is_a_testing | grep -c test

I could use this python code to execute the above shell command in python,

>>> import subprocess
>>> subprocess.check_output("echo This_is_a_testing | grep -c test", shell=True)
'1\n'

However, as I do not want to use the "shell=True" option, I tried the following python code,

>>> import subprocess
>>> p1 = subprocess.Popen(["echo", "This_is_a_testing"], stdout=subprocess.PIPE)
>>> p2 = subprocess.Popen(["grep", "-c", "test"], stdin=p1.stdout)
>>> p1.stdout.close()
>>> p2.communicate()
(None, None)

I wonder why the output is "None" as I have referred to the descriptions in the webpage : http://docs.python.org/library/subprocess.html#subprocess.PIPE

Had I missed some points in my code ? Any suggestion / idea ? Thanks in advance.

解决方案

From the manual:

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

p2 = subprocess.Popen(["grep", "-c", "test"], stdin=p1.stdout, stdout=subprocess.PIPE)

这篇关于Python - 如何使用管道执行 shell 命令,但没有“shell=True"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆