问题
I just started working with python subprocess module.
The code subprocess.call("ls", shell = False) and subprocess.call("ls", shell = True)
both return the same results. I just want to know what is the main difference between the two shell options.
回答1:
Straight out of the Docs:
If shell is True, the specified command will be executed through the shell. This can be useful if you are using Python primarily for the enhanced control flow it offers over most system shells and still want convenient access to other shell features such as shell pipes, filename wildcards, environment variable expansion, and expansion of ~ to a user’s home directory. However, note that Python itself offers implementations of many shell-like features (in particular, glob, fnmatch, os.walk(), os.path.expandvars(), os.path.expanduser(), and shutil).
This can open your code to shell injection techniques which can be better explained here:
Shell Injection Shell=True
On a windows machine for example, if shell was set as false, see below:
import subprocess
subprocess.Popen("dir", shell = False)
When run this code shall return a WindowsError: [Error 2]
stating that the specified file can not be found. However if shell is True, an object shall be returned. This is because 'dir'
is being 'piped' through cmd, and therefore, builtin commands such as dir will work.
The same works with subprocess.call.
来源:https://stackoverflow.com/questions/38408908/difference-between-shell-true-or-false-in-python-subprocess