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

标签 python windows logging file-permissions temporary-directory

我有一些代码在 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 中实例化记录器,希望不会持续存在对处理程序的引用——无论如何,我仍然看到这个错误。

我该如何解决这个问题?

最佳答案

您需要关闭处理程序,它会关闭文件。然后删除临时目录应该有效。我做了如下修改:

# 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

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

接下来,它似乎起作用了:

~> 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

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

关于python - 为什么无法在 Windows 上清除临时目录中我的文件处理程序的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59833204/

相关文章:

python - 使用嵌套迭代器有什么意义吗?

asp.net-mvc - 无法安装 Asp.net MVC 3

python - urllib.request.urlopen:SSL:Windows> = Vista(7/8/10/Server 2008)在Windows> = 3.4上的Windows上的SSL:CERTIFICATE_VERIFY_FAILED错误

sql - 我在哪里可以找到postgresql中的sql语句日志?

python - 使用 numpy 检查矩阵的每个部分是否全为 0

python - 使用 apply 用数据元组填充 Pandas 数据框行

ruby-on-rails - 记录 Elastic Beanstalk Node 应用程序

java - 仅当存在警告或更严重级别的日志事件时才记录所有级别

python - Django @property 计算模型字段 : FieldError: Cannot resolve keyword

ruby - 可执行 gem - Windows