我有一些代码在 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/