[英]How to pass this tar command as argument to python subprocess
If I am running the command that is specified in the args on the terminal then it goes successfully on terminal but doing the same in python program is not working; 如果我正在终端上的args中运行指定的命令,那么它会在终端上成功运行,但是在python程序中无法正常运行; I am seeing junk characters in the screen to the size of the input tar file and lot of xterm words too;
我在屏幕上看到的垃圾字符与输入的tar文件的大小以及许多xterm单词的大小有关;
I feel the problem is handling the ' ' letters in the args; 我觉得问题在于处理args中的''字母;
import subprocess
try:
args = "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz".split()
subprocess.check_call(args)
except subprocess.CalledProcessError as e:
print e
I am not specialist, but this i found - this commands not working in sh
, but working in bash
: 我不是专家,但是我发现了这一点-该命令在
sh
不起作用,但在bash
起作用:
$ sh -c "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz"
sh: -c: line 0: syntax error near unexpected token `('
sh: -c: line 0: `cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz'
$
$ bash -c "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz"
$
Thats a reason why it not work in subprocess directly. 这就是为什么它不能直接在子流程中工作的原因。 This code looks work fine:
这段代码看起来不错:
import subprocess
command = "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz"
subprocess.Popen(command, shell=True, executable='/bin/bash')
I tried a number of alternatives, and none of them were satisfactory. 我尝试了许多替代方法,但没有一个令人满意。 The best I found was switching over to
Popen
. 我发现最好的是切换到
Popen
。
# this should have the a similar signature to check_call
def run_in_shell(*args):
# unfortunately, `args` won't be escaped as it is actually a string argument to bash.
proc = subprocess.Popen(['/bin/bash', '-c', ' '.join(args)])
# This will also work, though I have found users who had problems with it.
# proc = subprocess.Popen(' '.join(args), shell=True, executable='/bin/bash')
stat = proc.wait()
if stat != 0:
subprocess.CalledProcessError(returncode=stat, cmd=command)
return stat
run_in_shell("cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz")
As a note: /bin/sh
has problems with the unescaped parentheses. 注意:
/bin/sh
的未转义括号有问题。 If you don't want to specify '/bin/bash'
above, then you will need to escape the paren: 如果您不想在上面指定
'/bin/bash'
,则需要转义括号:
args = 'cat parsing.tgz <\\(echo -n ''| gzip\\)> new-file.tgz'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.