Python 看门狗窗口等待复制完成

标签 python python-watchdog

我在 Windows 2012 服务器上使用 Python 看门狗模块来监控共享驱动器上出现的新文件。当看门狗注意到新文件时,它会启动数据库恢复过程。

但是,看门狗似乎会在文件创建后立即尝试恢复文件,而不是等到文件完成复制到共享驱动器。所以我将事件更改为 on_modified 但有两个 on_modified 事件,一个是文件最初被复制时,另一个是文件复制完成时。

如何处理两个 on_modified 事件,使其仅在文件复制到共享驱动器完成时触发?

同时将多个文件复制到共享驱动器时会发生什么情况?

这是我的代码

import time
import subprocess
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class NewFile(FileSystemEventHandler):
    def process(self, event):
        if event.is_directory:
            return

    if event.event_type == 'modified':            
        if getext(event.src_path) == 'gz':
            load_pgdump(event.src_path)

    def on_modified(self, event):
        self.process(event)

def getext(filename):
    "Get the file extension"
    file_ext = filename.split(".",1)[1]
    return file_ext

def load_pgdump(src_path):    
    restore = 'pg_restore command ' + src_path
    subprocess.call(restore, shell=True)

def main():
    event_handler = NewFile()
    observer = Observer()
    observer.schedule(event_handler, path='Y:\\', recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

if __name__ == '__main__':
    main()

最佳答案

在您的 on_modified 事件中,通过查看文件大小等待文件完成复制。

提供更简单的循环:

historicalSize = -1
while (historicalSize != os.path.getsize(filename)):
  historicalSize = os.path.getsize(filename)
  time.sleep(1)
print "file copy has now finished"

关于Python 看门狗窗口等待复制完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32092645/

相关文章:

python - Google Colab 从 colabdisk 读取文件而不是上传

python - 在 Jupyter LaTeX Markdown Cell 中使用 python 变量

python pandas 两个数据帧的复杂合并

Python Watchdog - 如何仅在创建文件时查看?

python - 尝试使用 pip 安装看门狗时如何修复 ‘“ERROR: Command errored out with exit status 1:”

python - 如何使用 Python 查看文件而不是目录的更改?

python - 为什么单精度和 double 比较在 numpy 中失败?

python - Django保存文件不使用表单,仅使用ajax

Python 看门狗重复事件

python - 如何正确运行Watchdog的RegexMatchingEventHandler?