我有一个 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
来确定文件复制(来自外部进程)是否已完成?
最佳答案
当文件或目录发生更改时,您应该依靠内核来通知您的程序。
在 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()
关于Python-从外部进程复制时如何知道文件是否完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20807851/