2016-03-02 27 views
0

我想完成一个想法,我真的不知道该怎么做。基本上我试图捕捉通过grep命令的值如下所示处理access_log与子流程的实时输出

p = subprocess.Popen('tail -f /data/qantasflight/run/tomcat/logs/localhost_access_log.2016-02-29.txt | grep /qantas-ui/int/price?', stdout=subprocess.PIPE, shell = True) 
stdout = p.communicate()[0] 

过程中的标准输出值,然后按下值如下所示

f = urllib.urlopen("http://162.16.1.90:9140/TxnService", params2) 

param2的是值,其中i将处理结果由subprocess.Popen

给出简而言之我想以下:

- 等待新值 - > - 过程的值 - > - 推值 - >

这应该是实时的,python脚本将继续获取新值,处理它,然后推送该值。

+0

1-为什么在这里使用外部进程,如'tail','grep'(特别是'grep')? 2相关:[Python:从subprocess.communicate()读取流输入)(http://stackoverflow.com/q/2715847/4279) – jfs

+0

为了澄清,你可以使用像'if'/ qantas-ui/int /价格':'代替'grep'在这里。 'tail -f'可以替换为''watchdog'包('$ pip install watchdog')](http://pythonhosted.org/watchdog/quickstart.html),虽然调用'tail -f'可能会更简单。 – jfs

回答

1

我尝试代码somethink,只要你想,但我只是在打印日志新的生产线,您可以处理线,推动

from __future__ import print_function 
import subprocess 
from time import sleep 

f = open('test.log', 'r') 
while True: 
    line = '' 
    while len(line) == 0 or line[-1] != '\n': 
     tail = f.readline() 
     if tail == '': 
      continue 
     line = tail 

    print(line, end='') 

这种打印新的生产线,以安慰,只是编辑和使用:)也许我帮助你:)

+0

你的代码有意义,但是当我运行它时,它会打开整个文件,然后开始阅读最新的结束行。如果我想阅读那些包含“/ qantas-ui/int/price?”的最新行,我应该做些什么修改? –

+0

如果你只想读取新行,就在'f = open(...)'后面写上'f.seek(0,2)'这个新行,然后在log中添加新行时,就解析它并根据需要处理 – sunny

+0

让我试试,我会尽快回复您。 –