在python中执行管道外壳命令
问题描述:
我需要帮助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)
答
你没有得到,因为这条线的任何结果:
['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)
现在,您的代码可以在任何平台上运行,而无需发出外部命令。它也可能更快。
答
谢谢。那我怎么开始我有超过10万行以上的文件。我必须在每个文件之间找到缺失的行。我没有得到我想要的结果。这就是为什么我想尝试系统命令的原因,但肯定会尝试while循环。
'shell = Ture'?当真? –
btw为什么要用'cat'? 'grep'可以在输入文件中输入一个文件 –
尝试使用'p1.communicate(),p2.communicate()'关闭文件并在得到结果后将它们全部放在最后 – Vinny