为什么当 args 是序列时 subprocess.Popen 不起作用? [英] Why subprocess.Popen doesn't work when args is sequence?

查看:56
本文介绍了为什么当 args 是序列时 subprocess.Popen 不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having a problem with subprocess.Popen when args parameter is given as sequence.

例如:

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

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

This works (it prints the correct size of /home/support/Maildir dir):

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

但是,这不起作用(试试看):

But, this doesn't work (try it):

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

怎么了?

推荐答案

来自 文档

在 Unix 上,shell=True: […] 如果 args 是一个序列,则第一项指定命令字符串和任何 附加项将被视为附加参数外壳本身.也就是说,Popen 的作用相当于:

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], ...])

这在您的情况下翻译为:

Which translates in your case to:

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

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

This means that -s, -b and maildir are interpreted as options by the shell, not by du (try it on the shell commandline!).

由于在您的情况下不需要 shell=True,因此您可以将其删除:

Since shell=True is not needed in your case anyway, you could just remove it:

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

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

Alternatively you could just use your orignal approach, but you don't need a list in that case. You would also have to take care of spaces in the directory name:

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

这篇关于为什么当 args 是序列时 subprocess.Popen 不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆