简体   繁体   English

Python如何在Linux Shell中使用子进程管道

[英]python how to use subprocess pipe with linux shell

I have a python script search for logs, it continuously output the logs found and I want to use linux pipe to filter the desired output. 我有一个python脚本搜索日志,它不断输出找到的日志,我想使用linux管道来过滤所需的输出。 example like that: 像这样的例子:

$python logsearch.py | $ python logsearch.py​​ | grep timeout grep超时

The problem is the sort and wc are blocked until the logsearch.py finishes, while the logsearch.py will continuous output the result. 问题是排序和wc被阻塞,直到logsearch.py​​完成,而logsearch.py​​将连续输出结果。

sample logsearch.py: 示例logsearch.py​​:

p = subprocess.Popen("ping google.com", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for line in p.stdout:
    print(line)

UPDATE: 更新:

figured out, just change the stdout in subprocess to sys.stdout, python will handle the pipe for you. 弄清楚,只需将子进程中的stdout更改为sys.stdout,python就会为您处理管道。

p = subprocess.Popen("ping -c 5 google.com", shell=True, stdout=**sys.stdout**)

Thanks for all of you help! 谢谢大家的帮助!

And why use grep? 为什么要使用grep? Why don't do all the stuff in Python? 为什么不使用Python做所有事情?

from subprocess import Popen, PIPE
p = Popen(['ping', 'google.com'], shell=False, stdin=PIPE, stdout=PIPE)

for line in p.stdout:
    if 'timeout' in line.split():
        # Process the error
        print("Timeout error!!")
    else:
        print(line)

UPDATE: 更新:
I change the Popen line as recommended @triplee. 我根据建议@triplee更改了Popen行。 Pros and cons in Actual meaning of 'shell=True' in subprocess 子过程中“ shell = True”的实际含义的利弊

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

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