python - 使用python如何同时对多个文件执行此代码?

标签 python

我想同时跟踪多个文件并将日志推送到抄写器。 我正在从配置文件中读取文件,然后我想跟踪每个文件并将日志发送给抄写员。 我尝试过的是仅发送第一个文件的日志,而不发送其他文件的日志。

我想对每个文件同时运行尾部,并同时发送每个文件的日志。

for l in Config.items('files'):
  print l[0]
  print l[1]
  filename = l[1]
  file = open(filename,'r')
  st_results = os.stat(l[1])
  st_size = st_results[6]
  file.seek(st_size)
  while 1:
    where = file.tell()
    line = file.readline()
    if not line:
      time.sleep(1)
      file.seek(where)
    else:
      print line, # already has newline
      category=l[0]
      message=line
      log_entry = scribe.LogEntry(category, message)
      socket = TSocket.TSocket(host='localhost', port=1463)
      transport = TTransport.TFramedTransport(socket)
      protocol = TBinaryProtocol.TBinaryProtocol(trans=transport, strictRead=False, strictWrite=False)
      client = scribe.Client(iprot=protocol, oprot=protocol)
      transport.open()
      result = client.Log(messages=[log_entry])
      transport.close()

最佳答案

尝试这样的事情(Inspired by this)

import threading

def monitor_file(l): 

    print l[0]
    print l[1]
    filename = l[1]
    file = open(filename,'r')
    st_results = os.stat(l[1])
    st_size = st_results[6]
    file.seek(st_size)
    while 1:
      where = file.tell()
      line = file.readline()
      if not line:
        time.sleep(1)
        file.seek(where)
      else:
        print line, # already has newline
        category=l[0]
        message=line
        log_entry = scribe.LogEntry(category, message)
        socket = TSocket.TSocket(host='localhost', port=1463)
        transport = TTransport.TFramedTransport(socket)
        protocol = TBinaryProtocol.TBinaryProtocol(trans=transport, strictRead=False,       strictWrite=False)
        client = scribe.Client(iprot=protocol, oprot=protocol)
        transport.open()
        result = client.Log(messages=[log_entry])
        transport.close()


for l in Config.items('files'):
    thread = threading.Thread(target=monitor_file, args=(l))

关于python - 使用python如何同时对多个文件执行此代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8588147/

相关文章:

python - 如何从信号中获取频率?

python - Python 中的 ImportError 是什么意思?

python - Django模型字段默认基于另一个模型字段

python - numpy python 快速有效地将非零值提升到二维数组的顶部

python - 列出正在运行的 Jupyter 笔记本和 token

java - 如何从可以进行 html 校正和 js 脚本编写的浏览器获取 html 内容?

python - 通过 Python 模块生成股票的平均日价格

python - 初始化 python Defaultdict

python - H5py 存储字符串列表列表

python - 没有发送(或接收)队列的 Unix Socket