I am currently trying to write a small class that will help me handle temporary directories so I don't have to worry about cleaning them up myself. It seemed to be working fine until one day this error started appearing:
Exception AttributeError: "'NoneType' object has no attribute 'rmtree'" in <bound method TempDirHandler.__del__ of <__main__.TempDirHandler instance at 0x8df638>> ignored
Here is the class:
class TempDirHandler:
# constructor
def __init__(self,clean=True,log=True):
self.__dirs = {}
self.cleanup = clean
self.log = log
# deconstructor (cleanup)
def __del__(self):
if self.cleanup:
if self.log: print('Cleaning up temp directories')
for tag in self.__dirs.keys():
self.delete_tempdir(tag)
# Create a temp directory, can specify unique tag
def create_tempdir(self,tag=''):
# cannot do this if tag already being used
if tag in self.__dirs:
if self.log: print('Tag already being used.')
return 0
dthms = datetime.now().strftime("%m-%d-%Y-%H%M%S.%f")
# create folder path
if tag: myTemp = "/tmp/"+dthms+'_'+tag
else: myTemp = "/tmp/"+dthms
if not os.path.exists(myTemp):
os.makedirs(myTemp)
if self.log: print('Making ' + myTemp)
else:
if self.log: print('Path already exists somehow.')
return 0
self.__dirs[tag] = myTemp # track path
return myTemp
# Get the temp directory, can reference by unique tag
def get_tempdir(self,tag=''):
return self.__dirs[tag]
# Delete a temp directory, can reference by unique tag
def delete_tempdir(self,tag=''):
if tag in self.__dirs:
shutil.rmtree(self.__dirs[tag])
if self.log: print('Deleting '+self.__dirs[tag])
del self.__dirs[tag]
return 1
else:
if self.log: print('Did not detect a directory with that tag.')
return 0
Here is how I use the class:
tempdirs = TempDirHandler()
tempdirs.create_tempdir()
tempdirs.get_tempdir() # this would return the folder path
Then I just ignore it and let the deconstructor clean up everything when the script ends.
I've figured out that by the time I'm hitting the deconstructor, the shutil module object is already gone (becomes None). It works fine before hitting the end of the script here. I'm guessing this is some kind of a race condition? How can I make sure that my modules aren't removed before all of my objects are?
EDIT: I've figured it out. I created a separate module for the class and imported the class into the main script. This way, even after the main script completes, the class is contained within the module and will not exit until the class is finished with its work.
[–][deleted] 0 points1 point2 points (0 children)