Python - 如何从外部进程复制时知道文件是否已完成

时间:2013-12-27 21:08:25

标签: python file filesystems

我有一个Python函数,作为一个“侦听器”,用于将文件添加到文件夹(来自外部进程)。

我目前正在使用无限循环执行此操作,其中我检查文件大小以停止增加(表示文件已完成放置在文件夹中,并且其余的python函数可以继续打开文件)

file_size = 0
while True:
    file_info = os.stat(file_path)
    if file_info.st_size == 0 or file_info.st_size > file_size:
        file_size = file_info.st_size
        sleep(1)
    else:
        break

这有效,但我知道这是一个黑客。每隔一秒轮询一次增加的file_size并不是最好的方法。

是否有另一种方法可以使用Python来确定文件副本(来自外部流程)是否已完成?

1 个答案:

答案 0 :(得分:3)

当文件或目录发生更改时,您应该依赖内核来通知程序。

在Linux上,您可以使用inotify或类似的库来利用https://github.com/seb-m/pyinotify系统调用。来自pyinotify示例:

import pyinotify

# Instanciate a new WatchManager (will be used to store watches).
wm = pyinotify.WatchManager()
# Associate this WatchManager with a Notifier (will be used to report and
# process events).
notifier = pyinotify.Notifier(wm)
# Add a new watch on /tmp for ALL_EVENTS.
wm.add_watch('/tmp', pyinotify.ALL_EVENTS)
# Loop forever and handle events.
notifier.loop()