[英]Python execute complex shell command
Hi I have to execute a shell command :diff <(ssh -n root@10.22.254.34 cat /vms/cloudburst.qcow2.*) <(ssh -n root@10.22.254.101 cat /vms/cloudburst.qcow2) I tried 嗨,我必须执行一个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()
However I am getting an error diff: extra operand cat 但是我得到一个错误差异:额外的操作数猫
I am pretty new to python. 我对python很陌生。 Any help would be appreciated
任何帮助,将不胜感激
You are using <(...)
(process substitution) syntax, which is interpreted by the shell. 您正在使用
<(...)
(进程替换)语法,该语法由Shell解释。 Provide shell=True
to Popen to get it to use a shell: 提供
shell=True
给Popen以使其使用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()
Since you don't want the Bourne shell (/bin/sh), use the executable argument to determine the shell to use. 由于您不希望使用Bourne shell(/ bin / sh),请使用可执行参数确定要使用的shell。
You are using a special syntax called process substitiution in your command line. 您在命令行中使用了一种特殊的语法,称为进程替换。 This is supported by most modern shells (bash, zsh), but not by /bin/sh.
大多数现代shell(bash,zsh)都支持此功能,但/ bin / sh不支持。 Therefore, the method suggested by Ned might not work.
因此,Ned建议的方法可能不起作用。 (It could, if another shell provides /bin/sh and does not "correctly emulate" sh's behaviour, but it is not guaranteed to).
(如果另一个shell提供了/ bin / sh并且没有“正确模拟” sh的行为,则可以,但是不能保证这样做)。 try this instead:
试试这个代替:
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()
This is basically what the shell=True parameter does, but with /bin/bash instead of /bin/sh (as described in the subprocess docs ). 基本上,这是shell = True参数的功能,但是使用/ bin / bash而不是/ bin / sh(如子过程docs中所述 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.