Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't remove() TemporaryFile in __del__. #5414

Merged
merged 1 commit into from
Apr 23, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions python/tvm/contrib/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
"""Common system utilities"""
import atexit
import os
import tempfile
import shutil
Expand All @@ -23,27 +24,46 @@
except ImportError:
fcntl = None


class TempDirectory(object):
"""Helper object to manage temp directory during testing.

Automatically removes the directory when it went out of scope.
"""

TEMPDIRS = set()
@classmethod
def remove_tempdirs(cls):
temp_dirs = getattr(cls, 'TEMPDIRS', None)
if temp_dirs is None:
return

for path in temp_dirs:
shutil.rmtree(path, ignore_errors=True)

cls.TEMPDIRS = None

def __init__(self, custom_path=None):
if custom_path:
os.mkdir(custom_path)
self.temp_dir = custom_path
else:
self.temp_dir = tempfile.mkdtemp()
self._rmtree = shutil.rmtree

self.TEMPDIRS.add(self.temp_dir)

def remove(self):
"""Remote the tmp dir"""
if self.temp_dir:
self._rmtree(self.temp_dir, ignore_errors=True)
shutil.rmtree(self.temp_dir, ignore_errors=True)
self.TEMPDIRS.remove(self.temp_dir)
self.temp_dir = None

def __del__(self):
temp_dirs = getattr(self, 'TEMPDIRS', None)
if temp_dirs is None:
# Do nothing if the atexit hook has already run.
return

self.remove()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let us still keep the remove here, so we can delete immediately, but also removes from the TEMPDIRs, checks if TEMPDIR still exists and run the remove in the del

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done


def relpath(self, name):
Expand Down Expand Up @@ -72,6 +92,9 @@ def listdir(self):
return os.listdir(self.temp_dir)


atexit.register(TempDirectory.remove_tempdirs)


def tempdir(custom_path=None):
"""Create temp dir which deletes the contents when exit.

Expand Down