greppy.py with syntax coloring

This HTML file was generated with Kalle's syntaxcolor.py


   1"""
   2Find lines matching specified regex in a text file. Basically a UI for
   3re.search().
   4By Kalle (http://qalle.net)
   5"""
   6
   7HELP_TEXT = """\
   8Find lines matching specified regex in a text file.
   9
  10Args: Regex Source Target
  11    Regex
  12        Regular expression. Default settings of Python's re module are used.
  13        Each input line is stripped of trailing whitespace before matching.
  14    Source
  15        Name of UTF-8 text file to read.
  16    Target
  17        Name of text file to (over)write. Will be UTF-8 with Unix newlines.\
  18"""
  19
  20import sys
  21import os.path
  22import re
  23
  24def filter(regex, sourceHnd, targetHnd):
  25    """Filter source file to target file with regex."""
  26
  27    sourceHnd.seek(0)
  28    targetHnd.seek(0)
  29
  30    for line in sourceHnd:
  31        line = line.rstrip()
  32        if regex.search(line) is not None:
  33            print(line, file = targetHnd)
  34
  35def main():
  36    if len(sys.argv) != 4:
  37        exit(HELP_TEXT)
  38
  39    # read args
  40    (regexStr, source, target) = sys.argv[1:]
  41
  42    # compile regex
  43    try:
  44        regex = re.compile(regexStr)
  45    except re.error:
  46        exit("Invalid regular expression.")
  47
  48    # source and target files must not be the same
  49    try:
  50        if os.path.samefile(source, target):
  51            exit("Source and target files must not be the same.")
  52    except OSError:
  53        pass
  54
  55    try:
  56        with open(source, "rt", encoding = "utf8") as sourceHnd, \
  57        open(target, "wt", encoding = "utf8", newline = "\n") as targetHnd:
  58            filter(regex, sourceHnd, targetHnd)
  59    except OSError:
  60        exit("Error reading source file or writing target file.")
  61
  62if __name__ == "__main__":
  63    main()