python - 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 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()
推荐阅读
- angularjs - Angularjs工厂检索api
- android - 两个启动器活动创建两个 APK
- c# - Visual Studio 2017 中缺少报告模板
- python - 多GPU(1080Ti)在tensorflow中不加速训练,在cifar10_estimator代码上测试
- wso2is - 如何构建/打包 wso2 api manager 身份服务器作为密钥管理器
- google-cloud-firestore - Firestore 使用 try await 检查文档是否已存在
- c# - C# HttpListener 类不适用于 Windows 10 版本 1803
- java - 带有参数化注解的 JUnit 集成测试
- google-cloud-build - Google Cloud Build 可以通过工件目录递归吗?
- azure - 为 OPC 发布者设置环境变量