简体   繁体   English

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

[英]Why subprocess.Popen doesn't work when args is sequence?

I'm having a problem with subprocess.Popen when args parameter is given as sequence. 当args参数作为序列给出时,我遇到了subprocess.Popen的问题。

For example: 例如:

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

This works (it prints the correct size of /home/support/Maildir dir): 这工作(它打印正确的/ home / support / Maildir目录大小):

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

What's wrong? 怎么了?

From the 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 . 在Unix上,shell = True:[...]如果args是一个序列,第一个项指定命令字符串,任何其他项将被视为shell本身的附加参数 That is to say, Popen does the equivalent of: 也就是说,Popen相当于:

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

Which translates in your case to: 在您的情况下翻译为:

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

This means that -s , -b and maildir are interpreted as options by the shell, not by du (try it on the shell commandline!). 这意味着-s-bmaildir被shell解释为选项,而不是du (在shell命令行上尝试它!)。

Since shell=True is not needed in your case anyway, you could just remove it: 因为在你的情况下不需要shell=True ,你可以删除它:

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]

From document , 文件

On Unix, with shell=True : If args is a string , it specifies the command string to execute through the shell. 在Unix上, shell = True :如果args是一个字符串 ,它指定要通过shell执行的命令字符串。 If args is a sequence , the first item specifies the command string, and any additional items will be treated as additional shell arguments. 如果args是一个序列 ,则第一个项指定命令字符串,任何其他项将被视为附加的shell参数。

So, Try 所以,试试吧

subprocess.Popen("du -s -b " + maildir, ...

or 要么

subprocess.Popen(["du","-s","-b",maildir], ...

它应该是["du", "-s", "-b", maildir]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM