gpt4 book ai didi

python - 为什么 subprocess.Popen 在 args 是序列时不起作用?

转载 作者:太空狗 更新时间:2023-10-29 21:20:29 27 4
gpt4 key购买 nike

当 args 参数作为序列给出时,我遇到了 subprocess.Popen 问题。

例如:

import subprocess
maildir = "/home/support/Maildir"

这有效(它打印出/home/support/Maildir 目录的正确大小):

size = subprocess.Popen(["du -s -b " + maildir], shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
print size

但是,这行不通(试试看):

size = subprocess.Popen(["du", "-s -b", maildir], shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]
print size

怎么了?

最佳答案

来自documentation

On Unix, with shell=True: […] If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself. That is to say, Popen does the equivalent of:

Popen(['/bin/sh', '-c', args[0], args[1], ...])

在您的案例中转化为:

Popen(['/bin/sh', '-c', 'du', '-s', '-b', maildir])

这意味着 -s-bmaildir 被 shell 解释为选项,而不是 du(在 shell 命令行上尝试!)。

因为无论如何您的情况都不需要 shell=True,所以您可以删除它:

size = subprocess.Popen(['du', '-s', '-b', maildir],
stdout=subprocess.PIPE).communicate()[0].split()[0]

或者,您可以只使用您原来的方法,但在这种情况下您不需要列表。您还必须注意目录名称中的空格:

size = subprocess.Popen('du -s -b "%s"' % maildir, shell=True,
stdout=subprocess.PIPE).communicate()[0].split()[0]

关于python - 为什么 subprocess.Popen 在 args 是序列时不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2400878/

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