我对如何正确使用 Python 的 subprocess 模块感到困惑,特别是 check_output 方法的第一个参数和shell
选项。查看下面交互式提示的输出。我将第一个参数作为列表传递,并取决于是否shell=True
设置后,我得到不同的输出。有人可以解释这是为什么以及输出的输出吗?
>>> import subprocess
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'
>>> subprocess.check_output(["echo", "Hello World!"], shell=True)
'\n'
现在,当我将第一个参数作为简单字符串而不是列表传递时,我得到了这个令人讨厌的堆栈跟踪。这是为什么?这是怎么回事?
>>> subprocess.check_output("echo Hello World!")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 537, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1228, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
但是,当我打开 shell=True 时,它就可以正常工作:
>>> subprocess.check_output("echo Hello World!", shell=True)
'Hello World!\n'
所以我有点困惑,当第一个参数在列表中而没有时它就起作用shell=True
然后作为一个简单的字符串使用shell=True
。我不明白什么shell=True
以及将第一个参数作为列表与字符串传递之间的区别。