我以前使用过的subprocess没有任何问题,由于某种原因,当我尝试与grep:
grepOut = subprocess.check_output("grep 'hello' tmp", shell=True)
我得到以下错误:
File "/usr/lib/python2.7/subprocess.py", line 544, in check_output raise CalledProcessError(retcode, cmd, output=output) subprocess.CalledProcessError: Command '['grep', "'hello'", 'tmp']' returned non-zero exit status 2
通过在terminal中直接input命令,我不会得到任何错误。
编辑:看到clemej的解释的答案
当shell = True时,你使用了错误的参数。
请参阅https://docs.python.org/2/library/subprocess.html
当你使用shell = True时,第一个参数不是字符串参数列表,而是命令字符串:
grepOut = subprocess.check_output("grep 'hello' tmp", shell=True)
应该管用。
您只需要在不指定shell = True的情况下使用列表形式,或者:
grepOut = subprocess.check_output(['grep', "'hello'", 'tmp'])
也应该工作。
你可以尝试的一件事是从标准错误流中读取,看看有什么问题。 你也可以使用call()并从stdout读取输出,从而忽略返回码。
正确的命令是: out = subprocess.check_output(['grep', 'hello', 'tmp'])
。
注意:没有shell=True
,引号内没有引号。
如果发生错误, grep
返回退出状态2。 在这种情况下,您的问题中的原始代码等同于调用grep
而没有任何不正确的参数:grep需要一个模式作为强制参数。