diff options
author | Serhiy Storchaka <storchaka@gmail.com> | 2019-03-30 06:33:02 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-03-30 06:33:02 (GMT) |
commit | 172bb39452ae8b3ccdf5d1f23ead46f44200cd49 (patch) | |
tree | 5e1effbca3664b839a81eb7a7d62fa4974cfbfb1 /Tools/scripts/rgrep.py | |
parent | afbb7a371fb44edc731344eab5b474ad8f7b57d7 (diff) | |
download | cpython-172bb39452ae8b3ccdf5d1f23ead46f44200cd49.zip cpython-172bb39452ae8b3ccdf5d1f23ead46f44200cd49.tar.gz cpython-172bb39452ae8b3ccdf5d1f23ead46f44200cd49.tar.bz2 |
bpo-22831: Use "with" to avoid possible fd leaks in tools (part 2). (GH-10927)
Diffstat (limited to 'Tools/scripts/rgrep.py')
-rwxr-xr-x | Tools/scripts/rgrep.py | 47 |
1 files changed, 24 insertions, 23 deletions
diff --git a/Tools/scripts/rgrep.py b/Tools/scripts/rgrep.py index 1917e05..c39bf93 100755 --- a/Tools/scripts/rgrep.py +++ b/Tools/scripts/rgrep.py @@ -30,29 +30,30 @@ def main(): f = open(filename) except IOError as msg: usage("can't open %r: %s" % (filename, msg), 1) - f.seek(0, 2) - pos = f.tell() - leftover = None - while pos > 0: - size = min(pos, bufsize) - pos = pos - size - f.seek(pos) - buffer = f.read(size) - lines = buffer.split("\n") - del buffer - if leftover is None: - if not lines[-1]: - del lines[-1] - else: - lines[-1] = lines[-1] + leftover - if pos > 0: - leftover = lines[0] - del lines[0] - else: - leftover = None - for line in reversed(lines): - if prog.search(line): - print(line) + with f: + f.seek(0, 2) + pos = f.tell() + leftover = None + while pos > 0: + size = min(pos, bufsize) + pos = pos - size + f.seek(pos) + buffer = f.read(size) + lines = buffer.split("\n") + del buffer + if leftover is None: + if not lines[-1]: + del lines[-1] + else: + lines[-1] = lines[-1] + leftover + if pos > 0: + leftover = lines[0] + del lines[0] + else: + leftover = None + for line in reversed(lines): + if prog.search(line): + print(line) def usage(msg, code=2): |