为什么按顺序使用 subprocess.check_output args 时没有错误
why no error when use subprocess.check_output args in sequence
我用python2.7
当我使用subprocess.check_output时,结果是正确的,没有文件aaa
>>> subprocess.check_output(['ls','-l','aaa'])
ls: cannot access aaa: No such file or directory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/subprocess.py", line 576, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['ls', '-l', 'aaa']' returned non-zero exit status 2
但是当我添加 shell=True
>>> subprocess.check_output(['ls','-l','aaa'],shell=True)
'test_multiprocess.py\ntest_threading.py\n'
结果不对,谁能帮帮我,告诉我为什么,谢谢
非常高级的解释。
设置shell=False
时(默认值),没有系统shell启动,所以第一个参数必须是可执行文件的路径,如果shell=True
表示系统 shell(例如:\bin\sh
)将首先启动。
所以基本上当 shell=False
是 subprocess.check_output(['ls','-l','aaa'])
并且当您通过 shell=True
时,您可以按以下方式传递 cmd subprocess.check_output('ls -l aaa',shell=True)
如果 shell=True
并且您将命令行参数作为列表传递,只有列表的第一个元素将被执行,其余的将被忽略或将改变 sh
行为,如果它包含有效的 shell 参数。
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)
shell=False
,args[:]
是命令行执行
shell=True
,args[0]
是要执行的命令行,args[1:]
是 sh. 的参数
我用python2.7
当我使用subprocess.check_output时,结果是正确的,没有文件aaa
>>> subprocess.check_output(['ls','-l','aaa'])
ls: cannot access aaa: No such file or directory
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python2.7/subprocess.py", line 576, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['ls', '-l', 'aaa']' returned non-zero exit status 2
但是当我添加 shell=True
>>> subprocess.check_output(['ls','-l','aaa'],shell=True)
'test_multiprocess.py\ntest_threading.py\n'
结果不对,谁能帮帮我,告诉我为什么,谢谢
非常高级的解释。
设置shell=False
时(默认值),没有系统shell启动,所以第一个参数必须是可执行文件的路径,如果shell=True
表示系统 shell(例如:\bin\sh
)将首先启动。
所以基本上当 shell=False
是 subprocess.check_output(['ls','-l','aaa'])
并且当您通过 shell=True
时,您可以按以下方式传递 cmd subprocess.check_output('ls -l aaa',shell=True)
如果 shell=True
并且您将命令行参数作为列表传递,只有列表的第一个元素将被执行,其余的将被忽略或将改变 sh
行为,如果它包含有效的 shell 参数。
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, cwd=None, encoding=None, errors=None, universal_newlines=None, timeout=None, text=None, **other_popen_kwargs)
shell=False
,args[:]
是命令行执行shell=True
,args[0]
是要执行的命令行,args[1:]
是 sh. 的参数