簡體   English   中英

Python執行復雜的shell命令

[英]Python execute complex shell command

嗨,我必須執行一個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()

但是我得到一個錯誤差異:額外的操作數貓

我對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。

您在命令行中使用了一種特殊的語法,稱為進程替換。 大多數現代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(如子過程docs中所述 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM