为什么无法在 Windows 上清理临时目录中的文件处理程序文件?

eri*_*rip 5 python windows logging file-permissions temporary-directory

我有一些代码可以在 UNIX 系统上正常运行,但不能在 Windows 上运行。我想让它跨平台,但我的头撞在墙上。最小重现如下:

文件一:foo.py

import os
import sys
import logging

logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger('foo')

def main(dir):
    logger.addHandler(logging.FileHandler(
        os.path.join(dir, 'temporary.log')
    ))

    logger.info("Hello, world!")
Run Code Online (Sandbox Code Playgroud)

文件2:main.py

from foo import main

import tempfile

if __name__ == "__main__":
    with tempfile.TemporaryDirectory("test") as tmp:
        main(tmp)
Run Code Online (Sandbox Code Playgroud)

我期望的是,将创建临时目录,在其中创建一个文件,向其发出日志,然后在tmp超出范围时将清除这两个文件。

相反,Windows 提供了一个错误:

PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: '...'
Run Code Online (Sandbox Code Playgroud)

我尝试过更改FileHandler远离追加模式的模式,我尝试过手动清理文件和目录,我尝试过延迟文件的创建,直到其记录并提高日志级别,并且我'我什至尝试在内部实例化记录器,foo.main希望不会保留对处理程序的引用 - 不管怎样,我仍然看到这个错误。

我怎样才能解决这个问题?

Vin*_*jip 4

您需要关闭处理程序,这将关闭文件。然后删除临时目录就可以了。我做了如下修改:

# foo.py
import os
import sys
import logging

logging.basicConfig(level=logging.INFO, stream=sys.stdout)
logger = logging.getLogger('foo')

def main(dir):
    h = logging.FileHandler(os.path.join(dir, 'temporary.log'))
    logger.addHandler(h)
    logger.info("Hello, world!")
    logger.removeHandler(h)
    return h
Run Code Online (Sandbox Code Playgroud)

# main.py
from foo import main

import tempfile

if __name__ == "__main__":
    with tempfile.TemporaryDirectory("test") as tmp:
        print('Using temp dir %s' % tmp)
        h = main(tmp)
        h.close()
Run Code Online (Sandbox Code Playgroud)

接下来,它似乎有效:

~> python3 c:\temp\main.py
Using temp dir C:\Users\Vinay\AppData\Local\Temp\tmp60qirkhutest
INFO:foo:Hello, world!

~> dir AppData\Local\Temp\tmp60qirkhutest
 Volume in drive C has no label.
 Volume Serial Number is D195-0C0D

 Directory of C:\Users\Vinay\AppData\Local\Temp

File Not Found
Run Code Online (Sandbox Code Playgroud)

如果您注释掉该h.close()行,它会像以前一样失败。