我有一些代码在 unix 系统上运行良好,但在 Windows 上运行良好。我想让它跨平台,但我的头撞到了墙上。最小复制如下:
文件 1: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!")
文件 2:main.py
from foo import main
import tempfile
if __name__ == "__main__":
with tempfile.TemporaryDirectory("test") as tmp:
main(tmp)
我期望的是临时目录将被创建,将在其中创建一个文件,日志将被发送到该文件,然后当tmp
超出范围时两者都将被清理。
相反,Windows 提供了一个错误:
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: '...'
我试过改变FileHandler
远离附加模式的模式,我试过手动清理文件和目录,我试过延迟文件的创建,直到它登录并提高日志级别,我'我什至尝试在内部实例化记录器foo.main
,希望不会持续存在对处理程序的引用——无论如何,我仍然看到这个错误。
我怎样才能解决这个问题?