整个字符串命令和popen中的字符串列表之间的区别

整个字符串命令和popen中的字符串列表之间的区别

问题描述:

我发现大多数程序员建议使用字符串列表来表示popen中的命令.但是,在我自己的项目中,我发现在更多情况下,整个字符串都可以工作.

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.

例如,以下作品

subprocess.Popen('pgrep -f "\./run"', stdout=subprocess.PIPE, shell=True).wait()

同时

subprocess.Popen(['pgrep', '-f', '"\./run"'], stdout=subprocess.PIPE, shell=True).wait()

没有.

我可以知道这两种实施方式之间的区别是什么,为什么第二种无法按预期工作?

May I know what's the difference between these two ways of implementation and why the second one does not work as expected?

第二个不应具有shell=True参数.相反,它应该是: subprocess.Popen(['pgrep', '-f', '"\./run"'], stdout=subprocess.PIPE).wait().

The second should not have a shell=True parameter. Instead, it should be: subprocess.Popen(['pgrep', '-f', '"\./run"'], stdout=subprocess.PIPE).wait().

shell参数设置是否在单独的shell中执行命令.也就是说,如果仅是为了执行命令而产生了一个新的外壳程序,则该外壳程序必须先解释该外壳程序,然后才能运行该命令.

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.

但是,在提供字符串列表时,这不会产生第二个shell,因此(最少)更快.最好使用它来处理变量输入,因为它避免了字符串插值.

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.

请参阅: https://stackoverflow.com/a/15109975/1730261