我们在测试期间使用 tempfile 模块生成临时文件和目录。我们最近也开始在 Windows 上进行测试,并遇到了一堆 Windows PermissionErrors。
我最初认为这可能是因为 Windows 与 Unix 不同,它不允许同时访问文件。当我查看代码时,即使没有同时访问文件也会发生这种情况。
一个常见的线程似乎是当我们在上下文中使用 tempfile 模块的结构时发生的错误(with 语句)。当我们使用手动 try-except-finally 时,错误就会消失。
我正在研究解决这个问题的方法,前面提到的 try-except-finally 也在讨论中。
其他人遇到过这个或有任何见解吗?
这是我们的测试功能(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():
测试工作。