diff -r 8a2755f6ae96 Lib/tempfile.py --- a/Lib/tempfile.py Thu Sep 18 19:45:04 2014 +0300 +++ b/Lib/tempfile.py Fri Sep 19 11:48:13 2014 +0300 @@ -690,9 +690,7 @@ class TemporaryDirectory(object): """ # Handle mkdtemp raising an exception - name = None _finalizer = None - _closed = False def __init__(self, suffix="", prefix=template, dir=None): self.name = mkdtemp(suffix, prefix, dir) @@ -717,8 +715,5 @@ class TemporaryDirectory(object): self.cleanup() def cleanup(self): - if self._finalizer is not None: - self._finalizer.detach() - if self.name is not None and not self._closed: + if self._finalizer is not None and self._finalizer.detach(): _shutil.rmtree(self.name) - self._closed = True diff -r 8a2755f6ae96 Lib/test/test_tempfile.py --- a/Lib/test/test_tempfile.py Thu Sep 18 19:45:04 2014 +0300 +++ b/Lib/test/test_tempfile.py Fri Sep 19 11:48:13 2014 +0300 @@ -1211,6 +1211,30 @@ class TestTemporaryDirectory(BaseTestCas self.assertNotIn("Exception ", err) self.assertIn("ResourceWarning: Implicitly cleaning up", err) + def test_exit_on_shutdown(self): + # Issue #22427 + with self.do_create() as dir: + code = """if True: + import sys + import tempfile + import warnings + + def generator(): + with tempfile.TemporaryDirectory(dir={dir!r}) as tmp: + yield tmp + g = generator() + sys.stdout.buffer.write(next(g).encode()) + + warnings.filterwarnings("always", category=ResourceWarning) + """.format(dir=dir) + rc, out, err = script_helper.assert_python_ok("-c", code) + tmp_name = out.decode().strip() + self.assertFalse(os.path.exists(tmp_name), + "TemporaryDirectory %s exists after cleanup" % tmp_name) + err = err.decode('utf-8', 'backslashreplace') + self.assertNotIn("Exception ", err) + self.assertIn("ResourceWarning: Implicitly cleaning up", err) + def test_warnings_on_cleanup(self): # ResourceWarning will be triggered by __del__ with self.do_create() as dir: