简体   繁体   English

在python中执行管道外壳命令

[英]executing piped shell commands in python

I need help with python code in executing multiple piped shell commands in python. 在执行python中的多个管道外壳命令时,我需要python代码帮助。 I have written the following code but I am getting error. 我已经编写了以下代码,但出现错误。 As I am passing the file to the command. 当我将文件传递给命令时。 Please let me know the correct process on how to execute multiple piped commands in python. 请让我知道有关如何在python中执行多个管道命令的正确过程。

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

is the shell command I want to execute. 是我要执行的shell命令。 Here is my python code. 这是我的python代码。 I am getting None when I run the code.I am redirecting the final output to a file. 我在运行代码时无提示,将最终输出重定向到文件中。

#!/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)

you're not getting any result because of this line: 由于此行,您没有得到任何结果:

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

this is passing "rtp1-vif" literally with quotes: no match. 实际上是用引号将"rtp1-vif"传递给了:无匹配项。

note that the whole piping process is overkill. 请注意,整个管道过程是过大的。 No need to use cat as the first grep can take the file as input. 不需要使用cat作为第一个grep可以将文件作为输入。

And to go further, it's really easy to perform that task in pure python. 更进一步,使用纯python执行该任务确实很容易。 Something like: 就像是:

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)

now your code can run on any platform, without the need to issue external commands. 现在,您的代码可以在任何平台上运行,而无需发出外部命令。 It's probably faster too. 它可能也更快。

Thank you. 谢谢。 That how I started I have a files with more than 100,000+ lines. 那就是我开始时拥有超过100,000行的文件的原因。 I have to find lines missing between each file. 我必须找到每个文件之间缺少的行。 I am not getting the results I want. 我没有得到想要的结果。 That is reason why I wanted to try system commands but will definitely try while loop. 这就是为什么我想尝试系统命令,但肯定会尝试while循环的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM