PageRenderTime 42ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/terminal/bin/highlight

http://github.com/rsms/workenv
Python | 55 lines | 49 code | 0 blank | 6 comment | 0 complexity | 8c638ac970a9c5867070682b639b936c MD5 | raw file
  1. #!/usr/bin/python -u
  2. # encoding: utf-8
  3. """
  4. Utility for highlighting keywords in terminals.
  5. Usage:
  6. $ python highlight -f /etc/passwd '/bin/false$'
  7. """
  8. import sys, re
  9. import optparse
  10. def colorize(string, regexps):
  11. for i, exp in regexps:
  12. col = (i % 7) + 31
  13. mod = ((i/7) + 1 % 2)
  14. string = exp.sub('\033[%d;%d;40m\g<0>\033[0m' % (mod, col), string)
  15. return string
  16. def main():
  17. parser = optparse.OptionParser(version="%prog 1.0",
  18. usage="usage: %prog [options] REGEX [...]")
  19. parser.add_option("-i", "--ignore-case", dest='ignore_case',
  20. action="store_true", default=False,
  21. help='be case insensitive')
  22. parser.add_option("-f", "--file", dest='file',
  23. metavar="F", default=None,
  24. help='read data from F (default is stdin)')
  25. options, args = parser.parse_args()
  26. if not args:
  27. parser.error("You must specify REGEX!")
  28. regexps = []
  29. for i,pattern in enumerate(args):
  30. if options.ignore_case:
  31. regexps.append( (i, re.compile(pattern, re.I)) )
  32. else:
  33. regexps.append( (i, re.compile(pattern)) )
  34. file = sys.stdin
  35. if options.file:
  36. file = open(options.file)
  37. while 1:
  38. # we need to do this in order to avoid multiline buffering
  39. line = file.readline()
  40. if not line:
  41. break
  42. sys.stdout.write(colorize(line, regexps))
  43. if __name__ == '__main__':
  44. try:
  45. main()
  46. except KeyboardInterrupt:
  47. sys.stdout.flush()
  48. sys.stderr.flush()