python - 等待 Windows 文件 I/O 在 Python 中完成

标签 python windows

我有一组系统测试,可以启动一些进程、创建文件等,然后将它们全部关闭并删除文件。

我在清理时遇到了两个间歇性错误:

在由其中一个进程创建的日志文件上:

    os.remove(log_path)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process: <path_to_file>

当尝试使用 shutil.rmtree 删除输出目录时:

File "C:\Python27\lib\shutil.py", line 254, in rmtree
    os.rmdir(path)
WindowsError: [Error 145] The directory is not empty: 'C:\\TestTarget\\xxx'

如果我在整理之前插入 2 秒的延迟,这两个错误都会消失,所以我认为问题在于 Windows 释放文件所花费的时间。显然,我想避免在我的测试中造成延迟,有没有办法等到文件系统 catch 进度?

最佳答案

我遇到了类似的问题,我搜索了几个月的正确解决方案,但一无所获。对我来说,问题只发生在使用 python2.7 在 Windows 上运行我的脚本时。大多数时候在 python3 上没有问题。在 GNU/Linux 上,我可以在没有这个肮脏解决方案的情况下使用文件操作。

我最终将这个函数用于 Windows 的任何文件操作:try_fail_wait_repeat(见下文),你应该做类似的事情。您也可以将 sleep 设置为不同的值。

import sys
import shutil
import time
import os

IS_WINDOWS = (sys.platform == "win32")


if IS_WINDOWS:
    maximum_number_of_tries = 40
    def move_folder(src, dst): 
        return try_fail_wait_repeat(maximum_number_of_tries, _move_dir, src, dst)
    def read_file(path): 
        return try_fail_wait_repeat(maximum_number_of_tries, _read_file, path)
else:
    def move_folder(src, dst):
        return shutil.move(src, dst)
    
    def read_file(path):
        return _read_file(path)


def _read_file(file_path):
    with open(file_path, "rb") as f_in:
        data = f_in.read().decode("ISO-8859-1")
    return data


def try_fail_wait_repeat(maximum_number_of_tries, func, *args):
    """A dirty solution for a dirty bug in windows python2"""
    i = 0
    while True:
        try:
            res = func(*list(args))
            return res
        except WindowsError as e:
            i += 1
            time.sleep(0.5)
            if i > maximum_number_of_tries:
                print("Too much trying to run {}({})".format(func, args))
                raise e

关于python - 等待 Windows 文件 I/O 在 Python 中完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21697867/

相关文章:

python - 为什么 signal.SIGALRM 在 Windows 上的 Python 中不起作用?

python - 如何显示找到正则表达式匹配项的行数

python - 从字符串末尾开始的非贪婪 Python 正则表达式

python - 将集合添加到集合并制作嵌套集合

linux - 使用 TeamViewer 在 Windows xp 上远程安装 Linux

windows - 使用 Inno Setup 安装时使应用程序自动随 Windows 启动的选项

python - 在 python 中编辑 CSV 文件,该文件从 python 中的另一个 json 文件读取值

python - 修改函数以在 Python 中使用列表理解

windows - 导航到分组 GridView 中的特定组标题(win store app)

python - 我如何防止用户在 Windows 上的 python 脚本中关闭我的 cmd 窗口