Python - 如何从外部进程复制文件时是否完成 [英] Python - How to know if a file is completed when copying from an outside process
问题描述
我有一个 Python
函数,它可以作为一个文件的监听器,用于添加到一个文件夹(来自外部进程)。
我目前正在使用无限循环来检查文件大小是否停止增加(表示文件已经放在文件夹中,其余的python函数可以去打开文件)。
file_size = 0
而True:
file_info = os.stat (file_path)
if file_info.st_size == 0或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 或类似的库。 I have a I am currently doing this using an infinite loop where I check for the file size to stop increasing (signifying that the file has finished being placed in the folder, and the rest of the python function can go on to open the file). This works, but I know its a hack. Polling an increasing file_size every one second doesn't seen like the best way to do this. Is there another way to use You should rely on the kernel to notify your program when a file or directory has changed. On Linux, you can take advantage of the inotify system call using: https://github.com/seb-m/pyinotify or similar libraries. From the
这篇关于Python - 如何从外部进程复制文件时是否完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
wm = pyinotify.WatchManager()
#将这个WatchManager与一个通告器关联起来(将被用来报告和
#进程事件)。
notifier = pyinotify.Notifier(wm)
在ALL_EVENTS的/ tmp上添加一个新的手表。
wm.add_watch('/ tmp',pyinotify.ALL_EVENTS)
#永久循环并处理事件。
notifier.loop()
Python
function that acts as a "listener" for a file to be added to a folder (from an external process).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
Python
to determine if an file copy (from an external process) has completed?pyinotify
examples: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()