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

时间:2016-01-27 03:30:55

标签: python shell command popen

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

例如,以下作品

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

,而

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

没有。

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

1 个答案:

答案 0 :(得分:1)

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

shell参数设置是否在单独的shell中执行命令。也就是说,如果要生成一个新的shell只是为了执行该命令,在运行之前必须由shell解释该命令。

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

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