diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2014-06-09 10:32:34 (GMT) |
---|---|---|
committer | Serhiy Storchaka <storchaka@gmail.com> | 2014-06-09 10:32:34 (GMT) |
commit | f10063e3c3dcd5fe5b99858fc618c574b6df7bf2 (patch) | |
tree | d549bcb1c89abdf86860b884f96b06c3aa846da9 /Lib/_pyio.py | |
parent | 8a8f7f983099f172d1f7c25d4fd99f5c0eb14072 (diff) | |
download | cpython-f10063e3c3dcd5fe5b99858fc618c574b6df7bf2.zip cpython-f10063e3c3dcd5fe5b99858fc618c574b6df7bf2.tar.gz cpython-f10063e3c3dcd5fe5b99858fc618c574b6df7bf2.tar.bz2 |
Issue #21310: Fixed possible resource leak in failed open().
Diffstat (limited to 'Lib/_pyio.py')
-rw-r--r-- | Lib/_pyio.py | 67 |
1 files changed, 37 insertions, 30 deletions
diff --git a/Lib/_pyio.py b/Lib/_pyio.py index b04d23a..d4cfb6e 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -200,38 +200,45 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None, (appending and "a" or "") + (updating and "+" or ""), closefd, opener=opener) - line_buffering = False - if buffering == 1 or buffering < 0 and raw.isatty(): - buffering = -1 - line_buffering = True - if buffering < 0: - buffering = DEFAULT_BUFFER_SIZE - try: - bs = os.fstat(raw.fileno()).st_blksize - except (OSError, AttributeError): - pass + result = raw + try: + line_buffering = False + if buffering == 1 or buffering < 0 and raw.isatty(): + buffering = -1 + line_buffering = True + if buffering < 0: + buffering = DEFAULT_BUFFER_SIZE + try: + bs = os.fstat(raw.fileno()).st_blksize + except (OSError, AttributeError): + pass + else: + if bs > 1: + buffering = bs + if buffering < 0: + raise ValueError("invalid buffering size") + if buffering == 0: + if binary: + return result + raise ValueError("can't have unbuffered text I/O") + if updating: + buffer = BufferedRandom(raw, buffering) + elif creating or writing or appending: + buffer = BufferedWriter(raw, buffering) + elif reading: + buffer = BufferedReader(raw, buffering) else: - if bs > 1: - buffering = bs - if buffering < 0: - raise ValueError("invalid buffering size") - if buffering == 0: + raise ValueError("unknown mode: %r" % mode) + result = buffer if binary: - return raw - raise ValueError("can't have unbuffered text I/O") - if updating: - buffer = BufferedRandom(raw, buffering) - elif creating or writing or appending: - buffer = BufferedWriter(raw, buffering) - elif reading: - buffer = BufferedReader(raw, buffering) - else: - raise ValueError("unknown mode: %r" % mode) - if binary: - return buffer - text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering) - text.mode = mode - return text + return result + text = TextIOWrapper(buffer, encoding, errors, newline, line_buffering) + result = text + text.mode = mode + return result + except: + result.close() + raise class DocDescriptor: |