Jui*_*icy 3 python linux subprocess
我之前使用过的子进程没有任何问题,出于某种原因,当我用grep尝试它时:
grepOut = subprocess.check_output("grep 'hello' tmp", shell=True)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
直接在终端中输入命令,我没有收到任何错误.
编辑:请参阅clemej的解释答案
当shell = True时,你使用了错误的参数.
请参阅https://docs.python.org/2/library/subprocess.html
当您使用shell = True时,第一个参数不是字符串参数列表,而是作为字符串的命令:
grepOut = subprocess.check_output("grep 'hello' tmp", shell=True)
Run Code Online (Sandbox Code Playgroud)
应该管用.
您只需在未指定shell = True时使用列表表单,因此可选:
grepOut = subprocess.check_output(['grep', "'hello'", 'tmp'])
Run Code Online (Sandbox Code Playgroud)
也应该工作.
| 归档时间: |
|
| 查看次数: |
9116 次 |
| 最近记录: |