【发布时间】:2015-05-09 04:20:37
【问题描述】:
我正在使用os.system 跟踪实时文件,grep 跟踪字符串
grep 成功后如何执行某些操作?
例如
cmd= os.system(tail -f file.log | grep -i abc)
if (cmd):
#Do something and continue tail
有什么办法可以做到吗?只有在os.system语句完成后才会到if块。
【问题讨论】:
我正在使用os.system 跟踪实时文件,grep 跟踪字符串
grep 成功后如何执行某些操作?
例如
cmd= os.system(tail -f file.log | grep -i abc)
if (cmd):
#Do something and continue tail
有什么办法可以做到吗?只有在os.system语句完成后才会到if块。
【问题讨论】:
您可以使用subprocess.Popen 并从标准输出读取行:
import subprocess
def tail(filename):
process = subprocess.Popen(['tail', '-F', filename], stdout=subprocess.PIPE)
while True:
line = process.stdout.readline()
if not line:
process.terminate()
return
yield line
例如:
for line in tail('test.log'):
if line.startswith('error'):
print('Error:', line)
【讨论】:
我不确定您是否真的需要在 python 中执行此操作 - 也许将 tail-f 输出通过管道传输到 awk 会更容易:https://superuser.com/questions/742238/piping-tail-f-into-awk
如果你想在python中工作(因为你需要在之后做一些处理)然后查看这个链接如何使用tail -f:How can I tail a log file in Python?
【讨论】: