【问题标题】:Python : Read all files in directory to watch inside while loopPython:读取目录中的所有文件以在while循环中观看
【发布时间】:2020-11-12 07:27:54
【问题描述】:

我正在编写一个 python 脚本,我将在其中传递一个目录,我需要从中获取所有日志文件。目前,我有一个小脚本,用于监视对这些文件的任何更改,然后处理这些信息。

它运行良好,但仅适用于单个文件和硬编码文件值。如何将目录传递给它,并且仍然可以查看所有文件。我的困惑是因为我在一个应该始终保持运行的 while 循环中处理这些文件,我该如何为目录中的 n 个文件执行此操作?

当前代码:

import time

f = open('/var/log/nginx/access.log', 'r')
while True:
    line = ''
    while len(line) == 0 or line[-1] != '\n':
        tail = f.readline()
        if tail == '':
            time.sleep(0.1)          # avoid busy waiting
            continue
        line += tail
        print(line)
        _process_line(line)

问题已被标记为重复,但要求是从目录内的所有文件中逐行获取更改。其他问题涉及单个文件,这已经在工作了。

【问题讨论】:

  • 您是否考虑过使用专为此用例设计的inotify
  • 这能回答你的问题吗? Monitoring contents of files/directories?
  • @SiHa 不,该页面上的任何答案都专门针对单个文件。如代码中所述,如何利用 inotify 逐行获取更改?
  • 对充满文件的目录逐行执行此操作是一种非常低效的方法,并且已经有可用的机制为您执行此操作而无需重新发明轮子。
  • @SiHa :我需要更改文件。看到这个:stackoverflow.com/questions/25350252/…Inotify 没有给出文件中的更改。

标签: python


【解决方案1】:

试试这个库:看门狗。

用于监控文件系统事件的 Python API 库和 shell 实用程序。

https://pythonhosted.org/watchdog/

简单example

import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s - %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S')
    path = sys.argv[1] if len(sys.argv) > 1 else '.'
    event_handler = LoggingEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

【讨论】:

  • 我认为你提到的路径是我应该通过的目录。我从哪里获得文件中发生的更改?
  • 这并没有给出实际的更改...文件是否被修改无关紧要,只有新的更改。 :-)
  • 您可以保存您阅读的最后一行,并在事件中 - 从那里阅读
【解决方案2】:

我不完全确定我是否理解您的尝试,但也许可以使用:

while True: 
    files = os.listdir(directory) 
    for file in files:
 
    --You're code for checking contents of the file--
     
              

【讨论】:

  • 行不通,因为我一直在拖尾文件....
猜你喜欢
  • 2018-04-17
  • 2014-11-10
  • 1970-01-01
  • 2019-07-28
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2013-12-02
  • 1970-01-01
相关资源
最近更新 更多