问题
I found most of the programmers suggest use list of strings to represent the command in popen. However, in my own project, I found a whole string works in more cases.
For example, the following works
subprocess.Popen('pgrep -f "\./run"', stdout=subprocess.PIPE, shell=True).wait()
while
subprocess.Popen(['pgrep', '-f', '"\./run"'], stdout=subprocess.PIPE, shell=True).wait()
does not.
May I know what's the difference between these two ways of implementation and why the second one does not work as expected?
回答1:
The second should not have a shell=True
parameter. Instead, it should be:
subprocess.Popen(['pgrep', '-f', '"\./run"'], stdout=subprocess.PIPE).wait()
.
The shell
parameter sets whether or not to execute the command in a separate shell. That is, if a new shell should be spawned just to execute the command, which must be interpreted by the shell before it can be run.
When providing a list of strings, however, this does not spawn a second shell, and thus is (minimally) faster. It is also better to use for processing variable input, because it avoids string interpolation.
See: https://stackoverflow.com/a/15109975/1730261
来源:https://stackoverflow.com/questions/35028357/difference-between-whole-string-command-and-list-of-strings-in-popen