首页 > 解决方案 > Python:读取目录中的所有文件以在while循环中观看

问题描述

我正在编写一个 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)

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

标签: python

解决方案


试试这个库:看门狗。

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

https://pythonhosted.org/watchdog/

简单的例子

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()

推荐阅读