I'm confused on how to correctly use Python's subprocess module, specifically, the check_output method's first argument and the shell
option. Check out the output from the interactive prompt below. I pass the first argument as a list and depending on whether shell=True
is set, I get different output. Can someone explain why this is and the output that is outputted?
>>> import subprocess
>>> subprocess.check_output(["echo", "Hello World!"])
'Hello World!\n'
>>> subprocess.check_output(["echo", "Hello World!"], shell=True)
'\n'
Now when I pass the first argument as a simple string instead of a list, I get this nasty stack trace. Why is that and what's going on here?
>>> 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
However, when I turn on shell=True, it then works perfectly:
>>> subprocess.check_output("echo Hello World!", shell=True)
'Hello World!\n'
So I'm a little confused, it works when the first arg is in a list WITHOUT shell=True
and then works as a simple string WITH shell=True
. I'm not understanding what shell=True
does and the difference between passing the first arg as a list vs a string.