diff --git a/Lib/tempfile.py b/Lib/tempfile.py index 448163f04380d5..dbc10a300f8799 100644 --- a/Lib/tempfile.py +++ b/Lib/tempfile.py @@ -543,12 +543,18 @@ def NamedTemporaryFile(mode='w+b', buffering=-1, encoding=None, file = _io.open(fd, mode, buffering=buffering, newline=newline, encoding=encoding, errors=errors) - return _TemporaryFileWrapper(file, name, delete) except BaseException: _os.unlink(name) _os.close(fd) raise + try: + return _TemporaryFileWrapper(file, name, delete) + except BaseException: + _os.unlink(name) + file.close() + raise + if _os.name != 'posix' or _sys.platform == 'cygwin': # On non-POSIX and Cygwin systems, assume that we cannot unlink a file # while it is open. diff --git a/Misc/NEWS.d/next/Library/2020-01-13-13-36-05.bpo-39318.236VwO.rst b/Misc/NEWS.d/next/Library/2020-01-13-13-36-05.bpo-39318.236VwO.rst new file mode 100644 index 00000000000000..7ce343179c3ba6 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2020-01-13-13-36-05.bpo-39318.236VwO.rst @@ -0,0 +1 @@ +Fix a file descriptor leak in NamedTemporaryFile under unusual circumstances. \ No newline at end of file