【问题标题】:Reading updated files on the fly in Python在 Python 中即时读取更新的文件
【发布时间】:2011-07-25 12:11:39
【问题描述】:

我正在编写两个都解析文件的 Python 脚本。一个是标准的 unix 日志文件,另一个是二进制文件。我正在尝试找出监控这些数据的最佳方法,以便在数据更新后立即读取数据。到目前为止,我发现的大多数解决方案都是特定于 linux 的,但我需要它才能在 FreeBSD 中工作。

显然,一种方法是每隔 X 时间运行一次我的脚本,但这似乎很粗暴且效率低下。如果我希望我的 Python 应用程序在后台连续运行并监视文件并在文件更改/更新后对其进行操作,那么我最好的选择是什么?

【问题讨论】:

  • 不能很好地处理二进制文件:)

标签: python parsing kqueue file-monitoring


【解决方案1】:

您尝试过 KQueue 事件吗?

http://docs.python.org/library/select.html#kqueue-objects

kqueue 是 inotify(文件更改通知服务)的 FreeBSD/OS 版本。这个我没用过,不过我觉得是你想要的。

【讨论】:

    【解决方案2】:

    我曾经为 Python 内置的解析器创建了一种守护进程。我需要查看一系列文件并用 Python 处理它们,而且它必须是一个真正的多操作系统解决方案(在这种情况下是 Windows 和 Linux)。我编写了一个程序,通过检查文件的修改时间来监视文件列表。程序会休眠一段时间,然后检查正在观看的文件的修改时间。如果修改时间比之前注册的时间新,则说明文件已更改,因此必须对此文件进行处理。

    类似这样的:

    import os
    import time
    
    path = os.path.dirname(__file__)
    print "Looking for files in", path, "..."
    
    # get interesting files
    files = [{"file" : f} for f in os.listdir(path) if os.path.isfile(f) and os.path.splitext(f)[1].lower() == ".src"]
    for f in files:
        f["output"] = os.path.splitext(f["file"])[0] + ".out"
        f["modtime"] = os.path.getmtime(f["file"]) - 10
        print "  watching:", f["file"]
    
    
    while True:
        # sleep for a while
        time.sleep(0.5)
        # check if anything changed
        for f in files:
            # is mod time of file is newer than the one registered?
            if os.path.getmtime(f["file"]) > f["modtime"]: 
                # store new time and...
                f["modtime"] = os.path.getmtime(f["file"])
                print f["file"], "has changed..."
                # do your stuff here
    

    它看起来不像一流的代码,但它工作得很好。

    还有其他关于此的 SO 问题,但我不知道他们是否会直接回答您的问题:

    How to implement a pythonic equivalent of tail -F?

    How do I watch a file for changes?

    How can I "watch" a file for modification / change?

    希望这会有所帮助!

    【讨论】:

    • 感谢您的回复。我希望有一个非轮询解决方案,但不确定是否可以从 kqueue 获得此功能。根据您的链接之一,我将检查看门狗,看看它是否有帮助。
    猜你喜欢
    • 1970-01-01
    • 2012-03-19
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    • 2014-02-21
    相关资源
    最近更新 更多