Python-如何使用管道执行Shell命令? [英] Python - how to execute shell commands with pipe?
问题描述
我有一种情况想要在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\n'
但是,由于我不想使用"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命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!