Skip to content

Commit 8f433fe

Browse files
author
Andrew Reusch
authored
Don't remove() TempDirectory in __del__ after atexit hook runs. (#5414)
* Use atexit to remove TempDirectory before interpreter shutdown. * Can't rely on complex functions from __del__ anyway. * Fixes warning message on my box: Exception ignored in: <function TempDirectory.__del__ at 0x12be10680> Traceback (most recent call last): File ".../tvm/python/tvm/contrib/util.py", line 55, in __del__ File ".../tvm/python/tvm/contrib/util.py", line 51, in remove File "/usr/local/opt/python/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 509, in rmtree AttributeError: 'NoneType' object has no attribute 'path'
1 parent 3ab3751 commit 8f433fe

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

python/tvm/contrib/util.py

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
# specific language governing permissions and limitations
1616
# under the License.
1717
"""Common system utilities"""
18+
import atexit
1819
import os
1920
import tempfile
2021
import shutil
@@ -23,27 +24,46 @@
2324
except ImportError:
2425
fcntl = None
2526

26-
2727
class TempDirectory(object):
2828
"""Helper object to manage temp directory during testing.
2929
3030
Automatically removes the directory when it went out of scope.
3131
"""
32+
33+
TEMPDIRS = set()
34+
@classmethod
35+
def remove_tempdirs(cls):
36+
temp_dirs = getattr(cls, 'TEMPDIRS', None)
37+
if temp_dirs is None:
38+
return
39+
40+
for path in temp_dirs:
41+
shutil.rmtree(path, ignore_errors=True)
42+
43+
cls.TEMPDIRS = None
44+
3245
def __init__(self, custom_path=None):
3346
if custom_path:
3447
os.mkdir(custom_path)
3548
self.temp_dir = custom_path
3649
else:
3750
self.temp_dir = tempfile.mkdtemp()
38-
self._rmtree = shutil.rmtree
51+
52+
self.TEMPDIRS.add(self.temp_dir)
3953

4054
def remove(self):
4155
"""Remote the tmp dir"""
4256
if self.temp_dir:
43-
self._rmtree(self.temp_dir, ignore_errors=True)
57+
shutil.rmtree(self.temp_dir, ignore_errors=True)
58+
self.TEMPDIRS.remove(self.temp_dir)
4459
self.temp_dir = None
4560

4661
def __del__(self):
62+
temp_dirs = getattr(self, 'TEMPDIRS', None)
63+
if temp_dirs is None:
64+
# Do nothing if the atexit hook has already run.
65+
return
66+
4767
self.remove()
4868

4969
def relpath(self, name):
@@ -72,6 +92,9 @@ def listdir(self):
7292
return os.listdir(self.temp_dir)
7393

7494

95+
atexit.register(TempDirectory.remove_tempdirs)
96+
97+
7598
def tempdir(custom_path=None):
7699
"""Create temp dir which deletes the contents when exit.
77100

0 commit comments

Comments
 (0)