Python - how to execute shell commands with pipe, but without #39;shell=True#39;?(Python - 如何使用管道执行shell命令,但没有shell = True?)
问题描述
我有一个案例想在 Python 中执行下面的 shell 命令并得到输出,
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
我可以使用这个python代码在python中执行上面的shell命令,
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
'
但是,由于我不想使用shell=True";选项,我尝试了下面的python代码,
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)
我想知道为什么输出是无"?正如我在网页中提到的描述:http://docs.python.org/library/subprocess.html#subprocess.PIPE
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.
推荐答案
来自手册:
要在结果元组中获得除 None 以外的任何内容,您需要给出stdout=PIPE 和/或 stderr=PIPE
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'?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python - 如何使用管道执行shell命令,但没有'shell = True'?


基础教程推荐
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01