Difference between whole string command and list of strings in popen

别说谁变了你拦得住时间么 提交于 2020-02-03 10:33:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!