2012-06-12 147 views
1

您好我必须执行一个shell命令:diff <(ssh -n [email protected] cat /vms/cloudburst.qcow2.*)<(ssh -n [email protected] cat /虚拟机/ cloudburst.qcow2) 我试图Python执行复杂shell命令

cmd="diff <(ssh -n [email protected] cat /vms/cloudburst.qcow2.*) <(ssh -n [email protected] cat /vms/cloudburst.qcow2)" 
args = shlex.split(cmd) 
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate() 

但是我收到一个错误DIFF:额外的操作猫

我很新的蟒蛇。任何帮助,将不胜感激

+0

您正在将参数“<(ssh”,“-n”,“root @ ...”,“cat”字面地传递给diff工具。在shell中输入时,“<(...) “部分首先得到评估,并且生成的(文件)作为参数传递给diff命令。您使用的是什么shell? – niko

+0

我正在使用bash – neorg

回答

7

您正在使用<(...)(进程替换)的语法,由shell解释。提供shell=True到POPEN得到它使用shell:

cmd = "diff <(ssh -n [email protected] cat /vms/cloudburst.qcow2.*) <(ssh -n [email protected] cat /vms/cloudburst.qcow2)" 
output,error = subprocess.Popen(cmd, shell=True, executable="/bin/bash", stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 

既然你不想要的是Bourne shell(/ bin/sh的),使用可执行参数来确定要使用的外壳。

+0

我试过了,但是我得到一个错误'/ bin/sh:语法错误:“(”unexpected“。 – neorg

+0

已更新,以显示如何指示要使用的外壳。 –

3

您在命令行中使用了一种称为process substitiution的特殊语法。这由大多数现代shell(bash,zsh)支持,但不支持/ bin/sh。因此,Ned建议的方法可能不起作用。 (如果另一个shell提供了/ bin/sh并且没有“正确模拟”sh的行为,但它不能保证)。 试试这个:

cmd = "diff <(ssh -n [email protected] cat /vms/cloudburst.qcow2.*) <(ssh -n [email protected] cat /vms/cloudburst.qcow2)" 
output,error = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() 

这基本上就是壳= True参数,不过它/斌/庆典而不是/ bin/sh的(如subprocess docs描述)。

+0

感谢您的快速响应。它工作正常!:) – neorg

+0

完美!简单,有效 –