Windows PermissionError & 临时文件模块

Windows PermissionError & tempfile module

我们在测试期间使用 tempfile 模块生成临时文件和目录。 我们最近也开始测试 Windows 和 运行 一堆 Windows PermissionErrors。

我最初认为这可能是因为Windows,不像Unix不允许同时访问一个文件。当我查看代码时,即使没有同时访问文件也会发生这种情况。

一个常见的线程似乎是我们在上下文中使用临时文件模块的结构(with 语句)时发生的错误。当我们使用手动 try-except-finally 时错误消失。

我正在研究解决此问题的方法,前面提到的 try-except-finally 也在 table 上。

还有其他人遇到过这个问题或有任何见解吗?

这是我们的测试函数(nosetests 但我不认为这是问题所在)

from nibabel.tmpdirs import InTemporaryDirectory
def test_high_level_glm_with_data():
    with InTemporaryDirectory():
        shapes, rk = ((7, 8, 7, 15), (7, 8, 7, 16)), 3
        mask, fmri_data, design_matrices = write_fake_fmri_data(shapes, rk)
        multi_session_model = FirstLevelModel(mask=mask).fit(
            fmri_data, design_matrices=design_matrices)
        z_image = multi_session_model.compute_contrast(
            np.eye(rk)[:2], output_type='z_score')
        variance_image = multi_session_model.compute_contrast(
            np.eye(rk)[:2], output_type='effect_variance')

        assert_array_equal(z_image.get_data() == 0., load(mask).get_data() == 0.)  # no error
        assert_true(
            (variance_image.get_data()[load(mask).get_data() > 0] > .001).all())  # error

这是回溯:

Traceback (most recent call last):
  File "C:\Users\kshit\AppData\Local\conda\conda\envs\nistats-py37-latest\lib\site-packages\nose\case.py", line 197, in runTest
    self.test(*self.arg)
  File "C:\Users\kshit\OneDrive\workspace\nistats-org\nistats-repo\kchawla-pi\nistats\nistats\tests\test_first_level_model.py", line 104, in test_high_level_glm_with_data
    (variance_image.get_data()[load(mask).get_data() > 0] > .001).all())
  File "C:\Users\kshit\AppData\Local\conda\conda\envs\nistats-py37-latest\lib\site-packages\nibabel\tmpdirs.py", line 76, in __exit__
    return super(InTemporaryDirectory, self).__exit__(exc, value, tb)
  File "C:\Users\kshit\AppData\Local\conda\conda\envs\nistats-py37-latest\lib\site-packages\nibabel\tmpdirs.py", line 48, in __exit__
    self.cleanup()
  File "C:\Users\kshit\AppData\Local\conda\conda\envs\nistats-py37-latest\lib\site-packages\nibabel\tmpdirs.py", line 44, in cleanup
    shutil.rmtree(self.name)
  File "C:\Users\kshit\AppData\Local\conda\conda\envs\nistats-py37-latest\lib\shutil.py", line 507, in rmtree
    return _rmtree_unsafe(path, onerror)
  File "C:\Users\kshit\AppData\Local\conda\conda\envs\nistats-py37-latest\lib\shutil.py", line 391, in _rmtree_unsafe
    onerror(os.unlink, fullname, sys.exc_info())
  File "C:\Users\kshit\AppData\Local\conda\conda\envs\nistats-py37-latest\lib\shutil.py", line 389, 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\kshit\AppData\Local\Temp\tmpbmgjqk03\mask.nii'

如果我不使用 with InTemporaryDir(): 测试有效。

用 Python 的 tempfile.TemporaryDirectory 替换 nibabel.tmpdirs.InTemporaryDirectory 解决了问题。

也许 Nibabel 的版本没有在清理前关闭文件?不知道这里发生了什么,这解决了我的问题。