用Python解析连续子进程并写入文件

用Python解析连续子进程并写入文件,python,python-2.7,Python,Python 2.7,我希望让我的Python(2.7.5)脚本不断地从一个连续的子进程中读取和解析时间戳和其他信息,使用系统时间进行时间戳差异,并将其写入一个文本文件。我将从通道访问调用camonitor实用程序作为进程。这类似于top,它将持续运行和更新数据,直到进程终止。在谷歌搜索和浏览了很多关于这里的帖子后,这就是我所拥有的。我想我缺少了一些将持续向文本文件添加数据的内容 import subprocess from Queue import Queue, Empty from threading impor

我希望让我的Python(2.7.5)脚本不断地从一个连续的子进程中读取和解析时间戳和其他信息,使用系统时间进行时间戳差异,并将其写入一个文本文件。我将从通道访问调用camonitor实用程序作为进程。这类似于top,它将持续运行和更新数据,直到进程终止。在谷歌搜索和浏览了很多关于这里的帖子后,这就是我所拥有的。我想我缺少了一些将持续向文本文件添加数据的内容

import subprocess
from Queue import Queue, Empty
from threading import Thread
from datetime import datetime
import time

class NonBlockingStreamReader:

    def __init__(self, stream):
        '''
        stream: stream to read from such as stdout
        '''
        self._s = stream
        self._q = Queue()

        def _populateQueue(stream, queue):
            '''
            collect lines from 'stream' and put them in 'queue'
            '''
            while True:
                line = stream.readline()
                if line:
                    queue.put(line)
                else:
                    raise UnexpectedEndOfStream

        self._t = Thread(target = _populateQueue, args = (self._s, self._q))
        self._t.daemon = True
        self._t.start() # start collecting lines from thel stream

    def readline(self, timeout = None):
        try:
            return self._q.get(block = timeout is not None, timeout = timeout)

        except Empty:
            return None


class UnexpectedEndOfStream(Exception): pass

def caMonitor(signalList):

     cmd = ["camonitor"]
     # add signals to the camonitor command
     cmd.extend(signalList)

     print(cmd)

     process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
     # wrap process.stdout with a NonBlockingStreamReader object:
     nbsr = NonBlockingStreamReader(process.stdout)

     # get the output for  X seconds
     t_end = time.time() + 1

     fmt = "%H:%M:%S.%f"

     while time.time() < t_end:
        try:
              output = nbsr.readline(0.05)
              # 0.05 secs to get the results
              '''
              if not output:
                 print ('[No data]')
                 break
              '''
              signal = output[0:16]
              timestamp = output[42:57]
              now = datetime.now()
              sysTime = now.strftime("%H:%M:%S.%f")

              tstamp1 = datetime.strptime(timestamp, fmt)
              tstamp2 = datetime.strptime(sysTime, fmt)

              if tstamp1 > tstamp2:
                 td = tstamp1 - tstamp2
              else:
                 td = tstamp2 - tstamp1

              print(signal + ' ' + timestamp + ' systime ' + sysTime + ' delta: ' + str(td))

              with open('camonlog.log', 'a+') as f:
                 f.write(signal + ' ' + timestamp + ' systime ' + sysTime + ' delta: ' + str(td) + '\n')

        except TypeError:
              print "no data"
导入子流程
从队列导入队列,为空
从线程导入线程
从日期时间导入日期时间
导入时间
类非阻塞StreamReader:
定义初始化(自,流):
'''
流:要从中读取的流,如stdout
'''
self.\u s=流
self._q=Queue()
def_populateQueue(流,队列):
'''
从“流”收集行并将它们放入“队列”
'''
尽管如此:
line=stream.readline()
如果行:
队列.放置(行)
其他:
提出未预料到的Dofstream
self.\u t=Thread(target=\u populateQueue,args=(self.\u s,self.\u q))
self.\u t.daemon=True
self._.t.start()#开始从该流收集线路
def readline(自身,超时=无):
尝试:
返回self.\u q.get(block=timeout不是None,timeout=timeout)
除空外:
一无所获
类UnexpectedEndOfStream(异常):通过
def caMonitor(信号列表):
cmd=[“camonitor”]
#向camonitor命令添加信号
命令扩展(信号列表)
打印(cmd)
process=subprocess.Popen(cmd,stdout=subprocess.PIPE)
#使用非BlockingStreamReader对象包装process.stdout:
nbsr=非阻塞流标头(process.stdout)
#获得X秒的输出
t_end=time.time()+1
fmt=“%H:%M:%S.%f”
当time.time()结束时:
尝试:
输出=nbsr.读线(0.05)
#0.05秒获得结果
'''
如果没有输出:
打印(“[无数据]”)
打破
'''
信号=输出[0:16]
时间戳=输出[42:57]
now=datetime.now()
sysTime=now.strftime(“%H:%M:%S.%f”)
tstamp1=datetime.strtime(时间戳,fmt)
tstamp2=datetime.strtime(系统时间,fmt)
如果tstamp1>tstamp2:
td=tstamp1-tstamp2
其他:
td=tstamp2-tstamp1
打印(信号+时间戳+系统时间+系统时间+增量:'+str(td))
将open('camonlog.log','a+')作为f:
f、 写入(信号+''+时间戳+'systime'+systime+'delta:'+str(td)+'\n')
除类型错误外:
打印“无数据”

在类NonBlockingStreamReader中,如果流没有任何数据,populateQueue方法将引发unexpectedDofstream异常,线程将终止,并且不会监视您的流

因此,定义如下所示的方法:

def _populateQueue(stream, queue):
    while True:
        line = stream.readline()
        if line:
            queue.put(line)
        else:
            time.sleep(1)