Search for prog within the lines of the files in path. For the each file in the path directory, open the file and search each line for the matching pattern. If the pattern is found, write the file and line information to stdout (which is an OutputWindow).
(self, prog, path)
| 150 | sys.stdout = save |
| 151 | |
| 152 | def grep_it(self, prog, path): |
| 153 | """Search for prog within the lines of the files in path. |
| 154 | |
| 155 | For the each file in the path directory, open the file and |
| 156 | search each line for the matching pattern. If the pattern is |
| 157 | found, write the file and line information to stdout (which |
| 158 | is an OutputWindow). |
| 159 | |
| 160 | Args: |
| 161 | prog: The compiled, cooked search pattern. |
| 162 | path: String containing the search path. |
| 163 | """ |
| 164 | folder, filepat = os.path.split(path) |
| 165 | if not folder: |
| 166 | folder = os.curdir |
| 167 | filelist = sorted(findfiles(folder, filepat, self.recvar.get())) |
| 168 | self.close() |
| 169 | pat = self.engine.getpat() |
| 170 | print(f"Searching {pat!r} in {path} ...") |
| 171 | hits = 0 |
| 172 | try: |
| 173 | for fn in filelist: |
| 174 | try: |
| 175 | with open(fn, errors='replace') as f: |
| 176 | for lineno, line in enumerate(f, 1): |
| 177 | if line[-1:] == '\n': |
| 178 | line = line[:-1] |
| 179 | if prog.search(line): |
| 180 | sys.stdout.write(f"{fn}: {lineno}: {line}\n") |
| 181 | hits += 1 |
| 182 | except OSError as msg: |
| 183 | print(msg) |
| 184 | print(f"Hits found: {hits}\n(Hint: right-click to open locations.)" |
| 185 | if hits else "No hits.") |
| 186 | except AttributeError: |
| 187 | # Tk window has been closed, OutputWindow.text = None, |
| 188 | # so in OW.write, OW.text.insert fails. |
| 189 | pass |
| 190 | |
| 191 | |
| 192 | def _grep_dialog(parent): # htest # |