我在 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/