Python执行复杂的shell命令

时间:2012-06-12 18:59:15

标签: python

您好我必须执行一个shell命令:diff<(ssh -n root@10.22.254.34 cat /vms/cloudburst.qcow2.*)<(ssh -n root@10.22.254.101 cat / vms / cloudburst .qcow2) 我试过了

cmd="diff <(ssh -n root@10.22.254.34 cat /vms/cloudburst.qcow2.*) <(ssh -n root@10.22.254.101 cat /vms/cloudburst.qcow2)"
args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()

但是我得到一个错误diff:额外的操作数cat

我对python很新。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:7)

您正在使用<(...)(进程替换)语法,该语法由shell解释。向Popen提供shell=True以使其使用shell:

cmd = "diff <(ssh -n root@10.22.254.34 cat /vms/cloudburst.qcow2.*) <(ssh -n root@10.22.254.101 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),请使用executable参数来确定要使用的shell。

答案 1 :(得分:3)

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

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

这基本上是shell = True参数的作用,但使用/ bin / bash而不是/ bin / sh(如subprocess docs中所述)。

相关问题