Skip to main content
 首页 » 编程设计

Python执行复杂的shell命令

2025年05月04日11kerrycode

您好,我必须执行一个 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: extra operand cat

我是 python 的新手。任何帮助将不胜感激

请您参考如下方法:

您正在使用 <(...) (进程替换)语法,由 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() 

由于您不想要 Bourne shell (/bin/sh),请使用可执行参数来确定要使用的 shell。