diff options
author | achhina <amanschhina@gmail.com> | 2022-04-18 01:53:37 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-04-18 01:53:37 (GMT) |
commit | 328dbc051f84bd5fdf61101bb4fa61d85f8b7feb (patch) | |
tree | 3ffed19a8c924015e0a3bf6368f13fc450a9921d /Lib/argparse.py | |
parent | 7173fd5de0cb259b488828634745c03dbea94e6b (diff) | |
download | cpython-328dbc051f84bd5fdf61101bb4fa61d85f8b7feb.zip cpython-328dbc051f84bd5fdf61101bb4fa61d85f8b7feb.tar.gz cpython-328dbc051f84bd5fdf61101bb4fa61d85f8b7feb.tar.bz2 |
gh-85567: Register a cleanup function to close files for FileType objects in argparse (#32257)
* bpo-41395: Register a cleanup function to close files for FileType objects in argparse
* Added import as top level import, and renamed file as fh.
Diffstat (limited to 'Lib/argparse.py')
-rw-r--r-- | Lib/argparse.py | 10 |
1 files changed, 7 insertions, 3 deletions
diff --git a/Lib/argparse.py b/Lib/argparse.py index 429a72a..881dfda 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -84,7 +84,7 @@ __all__ = [ 'ZERO_OR_MORE', ] - +import atexit as _atexit import os as _os import re as _re import sys as _sys @@ -1268,8 +1268,12 @@ class FileType(object): # all other arguments are used as file names try: - return open(string, self._mode, self._bufsize, self._encoding, - self._errors) + fh = open(string, self._mode, self._bufsize, self._encoding, self._errors) + + # Register cleanup function to close file + _atexit.register(fh.close) + + return fh except OSError as e: args = {'filename': string, 'error': e} message = _("can't open '%(filename)s': %(error)s") |