gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 18:33:09 26 4
gpt4 key购买 nike

我发现大多数程序员建议使用字符串列表来表示 popen 中的命令。然而,在我自己的项目中,我发现一个完整的字符串在更多情况下有效。

例如下面的作品

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

同时

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

没有。

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

最佳答案

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

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

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

参见:https://stackoverflow.com/a/15109975/1730261

关于python - popen中整个字符串命令和字符串列表之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35028357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com