如何将此tar命令作为参数传递给python子进程
如果我正在运行在终端上的args中指定的命令,那么它在终端上成功执行,但在python程序中执行相同的操作不起作用;我看到屏幕上的垃圾字符与输入tar文件的大小以及许多xterm字词相同;如何将此tar命令作为参数传递给python子进程
我觉得问题在于处理参数中的''字母;
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
我尝试了一些替代方案,但都没有令人满意。我发现最好的是切换到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")
作为说明:/bin/sh
与未转义的括号存在问题。如果你不希望上述指定'/bin/bash'
,则需要逃跑的括号:
args = 'cat parsing.tgz <\\(echo -n ''| gzip\\)> new-file.tgz'
问题在于args中的特殊字符'',即使是shlex也不能识别这个特殊字符viswesn @ viswesn: 〜$ python tar.py cat parsing.tgz new-file.tgz /bin/sh:1:语法错误:“(”unexpected 命令'cat parsing.tgz new-file.tgz'返回非零退出状态2 – Viswesn
我不是专家,但我发现 - 此命令在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"
$
这就是为什么它不直接在子过程中工作的原因。此代码看起来工作正常:
import subprocess
command = "cat parsing.tgz <(echo -n ''| gzip)> new-file.tgz"
subprocess.Popen(command, shell=True, executable='/bin/bash')
是它的工作:)与bash,但我很惊讶为什么这不工作在:( – Viswesn
“不工作”是什么意思? – Chris
@Chris;我更新了我的问题,具体到您的意见。 – Viswesn
关闭主题,但不是使用'split()',而应该使用['shlex.split()'](https://docs.python.org/3.5/library/shlex.html#shlex.split)。 – squiguy