解释器关闭时发布Python`TemporaryDirectory`

时间:2019-06-04 08:17:04

标签: python temporary-files finalizer

我正在使用tempfile.TemporaryDirectory。我需要一个与我的程序一样长的目录。但是,当解释器关闭时,我确实遇到了一些问题。

考虑模拟示例:

import tempfile
import typing
import sys

class Foo:
   tempDir: tempfile.TemporaryDirectory
   file: typing.io

   def __del__():
      sys.stderr.write(''.join(['in finalizer ', self.tempDir.name, '\n']))
      self.file.close()
      self.tempDir.cleanUp()
      sys.stderr.write('finalizer done\n')

TemporaryDirectory自动注册一个终结器,以从磁盘中删除临时目录。我通过使用weakref.finalize来做到这一点。当解释器关闭时,我偶尔会看到两个终结器操作不合时宜:tempDir的终结器在上述__del__()方法之前称为 before 。在我的终结器中,我仍然对TemporaryDirectory有很好的参考。

这是我看到的错误消息:

Traceback (most recent call last):
  File "C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\weakref.py", line 624, in _exitfunc
    f()
  File "C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\weakref.py", line 548, in __call__
    return info.func(*info.args, **(info.kwargs or {}))
  File "C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\tempfile.py", line 799, in _cleanup
    _shutil.rmtree(name)
  File "C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\shutil.py", line 494, in rmtree
    return _rmtree_unsafe(path, onerror)
  File "C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\shutil.py", line 389, in _rmtree_unsafe
    onerror(os.unlink, fullname, sys.exc_info())
  File "C:\Users\welterp\AppData\Local\Continuum\miniconda3\envs\qs3\lib\shutil.py", line 387, in _rmtree_unsafe
    os.unlink(fullname)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\welterp\\AppData\\Local\\Temp\\tmpd6ps3rj6\\scalarData.h5'
in finalizer C:\Users\welterp\AppData\Local\Temp\tmpd6ps3rj6
finalizer done

很明显,解释器在我之前触发了weakref终结器!

对我毫无意义。

0 个答案:

没有答案