Problem with ctypes and removing folder tree

Viewed 23

I have a problem with very simple code.

from ctypes import CDLL
import shutil

# The random library ztrace_maps.dll copied from C:\Windows\SysWOW64 to C:/DLL/

class Test:
    def __init__(self):
        self.dll = CDLL("C:/DLL/ztrace_maps.dll")
    def __del__(self):
        del self.dll
        shutil.rmtree("C:/DLL/")

test = Test()
del test
shutil.rmtree("C:/DLL/")

I am not able to remove the catalog with dll during the execution of the Python script. The Python console (in Pycharm) is working fine. I found a workaround with the execution separate Python script after the closing of the script but should be another possibility to clean resources.

Error:

Traceback (most recent call last):
  File "C:/test.py", line 14, in <module>
    shutil.rmtree("C:/DLL/")
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 740, in rmtree
    return _rmtree_unsafe(path, onerror)
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 618, in _rmtree_unsafe
    onerror(os.unlink, fullname, sys.exc_info())
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 616, in _rmtree_unsafe
    os.unlink(fullname)
PermissionError: [WinError 5] Access is denied: 'C:/DLL/ztrace_maps.dll'
Exception ignored in: <function Test.__del__ at 0x02F55EC8>
Traceback (most recent call last):
  File "C:/test.py", line 10, in __del__
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 740, in rmtree
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 618, in _rmtree_unsafe
  File "C:\python32\python-3.8.10\Lib\shutil.py", line 616, in _rmtree_unsafe
PermissionError: [WinError 5] Access is denied: 'C:/DLL/ztrace_maps.dll'

Process finished with exit code 1

I tested the other commands but with the same result.

2 Answers

DLL files aren't unloaded instantly when deleted, (or maybe not unloaded ever), so deleting the reference to the library doesn't help.

instead you should look into how to unload a DLL (which is somewhat platform dependent) as found in this link.

Thank you Ahmed AEK! The solution with FreeLibrary is working correctly.

from ctypes import CDLL
import shutil
import ctypes

# random library ztrace_maps.dll from C:\Windows\SysWOW64
# copied to C:/DLL/

class Test:
    def __init__(self):
        self.dll = CDLL("C:/DLL/ztrace_maps.dll")
        self._handle = self.dll._handle

    def __del__(self):
        ctypes.windll.kernel32.FreeLibrary(self._handle)
        shutil.rmtree("C:/DLL/")

test = Test()
del test
Related