2017-10-16 82 views
0

我需要幫助python代碼在python中執行多個管道外殼命令。 我寫了下面的代碼,但我得到錯誤。當我將文件傳遞給命令時。請讓我知道如何在python中執行多個管道命令的正確過程。在python中執行管道外殼命令

EG: cat file|grep -i hostname|grep -i fcid 

是我想要執行的shell命令。這是我的Python代碼。當我運行代碼時,我得到None。我將最終輸出重定向到一個文件。

#!/usr/bin/python3 

import subprocess 

op = open("text.txt",'w') 
file="rtp-gw1" 

print("file name is {}".format(file)) 
#cat file|grep -i "rtp1-VIF"|grep -i "fcid" 

#cmd ='cat file|grep -i "rtp1-vif"' 
p1 = subprocess.Popen(['cat',file],stdout=subprocess.PIPE, stderr=subprocess.PIPE,shell=True) 
p2 = subprocess.Popen(['grep','-i', '"rtp1-vif"',file], stdin=p1.stdout, stdout=subprocess.PIPE,stderr= subprocess.PIPE,shell=Ture) 
p1.stdout.close() 
p3 = subprocess.Popen(['grep', '-i',"fcid"],stdin=p1.stdout, stdout=op,stderr= subprocess.PIPE,shell=Ture) 
p2.stdout.close() 

result = p3.communicate()[0] 

print(result) 
+0

'shell = Ture'?當真? –

+0

btw爲什麼要用'cat'? 'grep'可以在輸入文件中輸入一個文件 –

+0

嘗試使用'p1.communicate(),p2.communicate()'關閉文件並在得到結果後將它們全部放在最後 – Vinny

回答

0

你沒有得到,因爲這條線的任何結果:

['grep','-i', '"rtp1-vif"'] 

這是通過"rtp1-vif"字面上引號:不匹配。

請注意,整個管道過程是矯枉過正。不需要使用cat,因爲第一個grep可以將該文件作爲輸入。

爲了更進一步,在純python中執行這個任務真的很容易。例如:

with open("text.txt",'w') as op: 
    file="rtp-gw1" 

    for line in file: 
     line = line.lower() 
     if "rtp1-vif" in line and "fcid" in line: 
      op.write(line) 

現在,您的代碼可以在任何平臺上運行,而無需發出外部命令。它也可能更快。

0

謝謝。那我怎麼開始我有超過10萬行以上的文件。我必須在每個文件之間找到缺失的行。我沒有得到我想要的結果。這就是爲什麼我想嘗試系統命令的原因,但肯定會嘗試while循環。