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

Ste*_*fan 6 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>
Run Code Online (Sandbox Code Playgroud)

尝试删除输出目录时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'
Run Code Online (Sandbox Code Playgroud)

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

Ros*_*hal -3

您正在使用的功能仅删除空目录

尝试使用:

import shutil
shutil.rmtree('/folder_path')
Run Code Online (Sandbox Code Playgroud)

另外,请尝试在关闭进程之前添加睡眠间隔。