我需要帮助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)
'shell = Ture'?当真? –
btw为什么要用'cat'? 'grep'可以在输入文件中输入一个文件 –
尝试使用'p1.communicate(),p2.communicate()'关闭文件并在得到结果后将它们全部放在最后 – Vinny