Python Subprocess.check_输出与grep:exit status 2
我以前使用过subprocess,但没有遇到任何问题,当我尝试使用grep时,出于某种原因:Python Subprocess.check_输出与grep:exit status 2,python,linux,subprocess,Python,Linux,Subprocess,我以前使用过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) su
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
直接在终端中键入命令不会导致任何错误
编辑:有关解释,请参见clemej的答案您可以尝试的一件事是从标准错误流中读取,以查看出了什么问题。您也可以使用call()从stdout读取输出,从而忽略返回代码。当shell=True时,您使用了错误的参数 看 使用shell=True时,第一个参数不是字符串参数列表,而是作为字符串的命令:
grepOut = subprocess.check_output("grep 'hello' tmp", shell=True)
应该有用
您只需要在不指定shell=True时使用列表表单,因此:
grepOut = subprocess.check_output(['grep', "'hello'", 'tmp'])
正确的命令是:
out=subprocess。检查输出(['grep','hello','tmp'])
注意:无shell=True
,引号内无引号
grep
如果发生错误,则返回退出状态2。在这种情况下,您问题中的原始代码相当于调用grep
,而没有任何不正确的参数:grep期望一个模式作为强制参数。很抱歉,我已经尝试过了,忘了提及。grepOut=subprocess.check_输出(“grep'hello'tmp”,shell=True)给出了相同的错误。但是,没有其他终端命令给我这个问题。编辑了主要问题,以反映我仍然存在使用您建议的解决方案的问题。您肯定吗?因为当我将你的测试剪切粘贴到我的python2.7安装中时(在通过'echo'hello>tmp'创建了一个文件tmp之后),subprocess.check_输出(“grep'hello'tmp”,shell=True)起作用,但原来的方式不起作用。你已经改变了问题,现在你得到了退出状态1。那很不一样。这意味着它在文件中找不到字符串hello。退出状态1!=退出状态2。退出状态1表示未找到字符串。退出状态2表示有错误。@clemej我很抱歉,当你发表评论时,我意识到了这一点,给了你答案!不要更改问题中的代码。现在,错误消息不再与代码对应。代码中的一个问题是列表参数与shell=True
一起使用,这会改变参数的含义。