diff options
author | Terry Jan Reedy <tjreedy@udel.edu> | 2013-06-22 22:26:51 (GMT) |
---|---|---|
committer | Terry Jan Reedy <tjreedy@udel.edu> | 2013-06-22 22:26:51 (GMT) |
commit | de3beb2617bd9bf56326502ea5964ca809bce017 (patch) | |
tree | 608f0c535e561dadec602d44a7a24dcf4909acd6 /Lib/idlelib/GrepDialog.py | |
parent | 9290dd14b02508a667165d2e98f3f99aad61764e (diff) | |
download | cpython-de3beb2617bd9bf56326502ea5964ca809bce017.zip cpython-de3beb2617bd9bf56326502ea5964ca809bce017.tar.gz cpython-de3beb2617bd9bf56326502ea5964ca809bce017.tar.bz2 |
#18151, part 2: Silence debug build resource warning for each file opened by
'Find in files' by replacing 'open with implicit close' by 'with open' in
GrepDialog method grep_it. Streamline code with enumerate(), direct file
iteration, and output tweak. Add test for this method, including output format.
Diffstat (limited to 'Lib/idlelib/GrepDialog.py')
-rw-r--r-- | Lib/idlelib/GrepDialog.py | 43 |
1 files changed, 19 insertions, 24 deletions
diff --git a/Lib/idlelib/GrepDialog.py b/Lib/idlelib/GrepDialog.py index 46d6304..2e07312 100644 --- a/Lib/idlelib/GrepDialog.py +++ b/Lib/idlelib/GrepDialog.py @@ -81,36 +81,24 @@ class GrepDialog(SearchDialogBase): hits = 0 for fn in list: try: - f = open(fn, errors='replace') + with open(fn, errors='replace') as f: + for lineno, line in enumerate(f, 1): + if line[-1:] == '\n': + line = line[:-1] + if prog.search(line): + sys.stdout.write("%s: %s: %s\n" % + (fn, lineno, line)) + hits += 1 except OSError as msg: print(msg) - continue - lineno = 0 - while 1: - block = f.readlines(100000) - if not block: - break - for line in block: - lineno = lineno + 1 - if line[-1:] == '\n': - line = line[:-1] - if prog.search(line): - sys.stdout.write("%s: %s: %s\n" % (fn, lineno, line)) - hits = hits + 1 - if hits: - if hits == 1: - s = "" - else: - s = "s" - print("Found", hits, "hit%s." % s) - print("(Hint: right-click to open locations.)") - else: - print("No hits.") + print(("Hits found: %s\n" + "(Hint: right-click to open locations.)" + % hits) if hits else "No hits.") def findfiles(self, dir, base, rec): try: names = os.listdir(dir or os.curdir) - except os.error as msg: + except OSerror as msg: print(msg) return [] list = [] @@ -131,3 +119,10 @@ class GrepDialog(SearchDialogBase): if self.top: self.top.grab_release() self.top.withdraw() + +if __name__ == "__main__": + # A human test is a bit tricky since EditorWindow() imports this module. + # Hence Idle must be restarted after editing this file for a live test. + import unittest + unittest.main('idlelib.idle_test.test_grep', verbosity=2, exit=False) + |