我有一个python脚本搜索日志,它不断地输出找到的日志,我想使用linux管道来过滤所需的输出。像这样的例子:
$python logsearch.py \ grep超时
问题是排序和wc被阻塞,直到logsearch.py完成,而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)更新:
知道了,只需将子进程中的stdout更改为sys.stdout,python将为您处理管道。
p = subprocess.Popen("ping -c 5 google.com", shell=True, stdout=**sys.stdout**)谢谢你们的帮助!
发布于 2016-10-09 21:37:18
为什么要使用grep?为什么不用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)更新:
我将Popen行更改为推荐的@triplee。Actual meaning of 'shell=True' in subprocess的利弊
https://stackoverflow.com/questions/39948459
复制相似问题