【问题标题】:PermissionError: [WinError 32] The process cannot access the file because it is being used by another process:PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:
【发布时间】:2015-11-13 17:04:01
【问题描述】:

我正在尝试测试我自己的反网络版本,可以在here 找到。但是,我正在使用 Python 的 unittest 模块对其进行测试。代码如下:

import unittest
from unittest.mock import patch
from antiweb import main
import sys
import os
import tempfile
import shutil

class Test_Antiweb(unittest.TestCase):


def setUp(self):

    self.test_dir = tempfile.mkdtemp()
    self.testfile_source ="#@start()\n\n#@include(test_area)\n\n#@start(test_area)\n#This is test_area text\n#@(test_area)"
    with open(os.path.join(self.test_dir, "testfile.py"), "w") as test:
        test.write(self.testfile_source)

def test_antiweb(self):
    self.test_args = ['antiweb.py', '-i', "-o docs", os.path.join(self.test_dir, "testfile.py")]
    with patch.object(sys, 'argv', self.test_args):
        success = main()
    self.assertTrue(success)

def tearDown(self):

    shutil.rmtree(self.test_dir)



if __name__ == '__main__':
    unittest.main()

一切正常,除了tearDown 函数。在没有tearDown 的情况下执行单元测试时,临时文件夹及其内容已完美创建。但是使用tearDown 函数我得到一个错误:

======================================================================
ERROR: test_antiweb (antiweb_tests.Test_Antiweb)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\<username>\Documents\GitHub\antiweb\antiweb_tests.py", line 29,      in tearDown
shutil.rmtree(self.test_dir)
File "C:\Python34\lib\shutil.py", line 478, in rmtree
return _rmtree_unsafe(path, onerror)
File "C:\Python34\lib\shutil.py", line 377, in _rmtree_unsafe
onerror(os.rmdir, path, sys.exc_info())
File "C:\Python34\lib\shutil.py", line 375, in _rmtree_unsafe
os.rmdir(path)
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\Users\\
<username>\\AppData\\Local\\Temp\\tmp3lk01fn5'

当我然后查看临时文件夹时,文件夹本身仍然存在,但现在是空的。在这里包含我的反网络文件太多了,所以如果你需要它,我会再次链接here

【问题讨论】:

  • 好的,我知道出了什么问题:
  • 在antiweb中,我将工作目录更改为临时文件夹,所以我在临时文件夹中。然后当我尝试删除我现在所在的文件夹时,我收到该错误^^
  • 我猜你现在必须自己回答这个问题:-)

标签: python python-unittest shutil


【解决方案1】:

我自己也遇到过这种情况。您的问题出在您的设置中

self.test_dir = tempfile.mkdtemp() 返回文件描述符和路径的元组。删除前需要关闭文件描述符。

def setUp(self):

    self.fd, self.test_dir = tempfile.mkdtemp()
...
def tearDown(self):
    os.close(self.fd)
    shutil.rmtree(self.test_dir)

有关更详细的说明,请参阅this article

【讨论】:

  • mkstemp 返回一个元组;其中mkdtemp 返回目录的绝对路径名。
猜你喜欢
  • 2015-01-28
  • 2017-06-02
  • 2021-09-21
  • 2019-11-26
  • 1970-01-01
  • 2020-10-31
  • 2018-10-28
  • 2022-11-14
  • 2021-07-13
相关资源
最近更新 更多