【问题标题】:Python - How to know if a file is completed when copying from an outside processPython - 从外部进程复制时如何知道文件是否完成
【发布时间】:2013-12-27 21:08:25
【问题描述】:

我有一个 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

这行得通,但我知道这是一个 hack。每秒轮询增加的 file_size 并不是最好的方法。

还有其他方法可以使用Python 来确定文件复制(来自外部进程)是否已完成?

【问题讨论】:

  • 请看看这是否有帮助:stackoverflow.com/questions/6825994/…
  • 您可以控制这个外部进程吗?通常将文件复制到临时文件,然后在完成后重命名以处理这种情况。
  • 在写入文件时,它可能已被锁定。也许您可以使用poixfile 模块检查其状态(或自己锁定)。

标签: python file filesystems


【解决方案1】:

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

在 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()

【讨论】:

  • 有 Windows 等价物吗?
猜你喜欢
  • 2015-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-08
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多