Python cmd的Subprocess.call

Python cmd的Subprocess.call,python,Python,我有以下命令在shell中工作: $ pv itunes20140910.tbz | sudo tar xpj -C /tmp 但是,当我尝试用python执行此操作时,它不起作用: >>> import subprocess >>> import shlex >>> cmd=shlex.split('pv itunes20140910.tbz | sudo tar xpj -C /tmp') >>> subprocess

我有以下命令在shell中工作:

$ pv itunes20140910.tbz | sudo tar xpj -C /tmp
但是,当我尝试用python执行此操作时,它不起作用:

>>> import subprocess
>>> import shlex
>>> cmd=shlex.split('pv itunes20140910.tbz | sudo tar xpj -C /tmp')
>>> subprocess.call(cmd)
pv: invalid option -- 'C'
Try `pv --help' for more information.
1

我在这里做错了什么,在python中运行的正确命令是什么?

使用
shell=True
参数。否则无法解释
|

subprocess.call('pv itunes20140910.tbz | sudo tar xpj -C /tmp', shell=True)

上面的答案没有我想要的结果(进度条),尽管命令运行时不会出错。以下是对我有效的方法:

>>> import shlex, subprocess
>>> p1 = subprocess.Popen(shlex.split('pv /tmp/itunes20140910.tbz'), stdout=subprocess.PIPE) #Set up the echo command and direct the output to a pipe
>>> subprocess.Popen(shlex.split('sudo tar xpj -C /tmp'), stdin=p1.stdout) #send p1's output to p2

不要使用
shlex.split
。只需直接传入字符串。您可能会遇到问题,因为您在此处使用的是
sudo
,这可能会出现密码提示。@CharlesDuffy除非您使用
shell=True
@dano,否则无法传递字符串,我并不认为这是一个问题--stdin和stdout没有重新连接,所以他们仍然应该去TTY,所以sudo应该仍然能够得到一个句柄来提示。@dano,不正确<如果传递字符串,默认情况下会设置code>shell=True。为什么传递
subprocess.Popen(shlex.split('some string'))
,而不仅仅是
subprocess.Popen(['some','string'))
?后者更健壮,因为它不需要为shlex的解释正确转义字符串。