| 563 | 1 #!/usr/bin/env python | 
|  | 2 | 
|  | 3 """ | 
|  | 4 grep through multiple directories | 
|  | 5 """ | 
|  | 6 | 
|  | 7 # TODO: use a python grep implemention v subshell (probably) | 
|  | 8 | 
|  | 9 import optparse | 
|  | 10 import os | 
|  | 11 import subprocess | 
|  | 12 import sys | 
|  | 13 | 
|  | 14 def main(args=sys.argv[1:]): | 
|  | 15 | 
|  | 16     # CLI | 
|  | 17     usage = '%prog [options] PATTERN DIRECTORY [DIRECTORY] [...]' | 
|  | 18     parser = optparse.OptionParser(usage=usage, description=__doc__) | 
|  | 19     parser.add_option('-f', '--files', dest='files', default='*', | 
|  | 20                       help="file pattern [DEFAULT: %default]") | 
|  | 21     parser.add_option('-g', '--grep', dest='grep', | 
|  | 22                       action='append', default=[], | 
|  | 23                       help="`grep` command [DEFAULT: grep]") | 
|  | 24     parser.add_option('-p', '--print', dest='print_commands', | 
|  | 25                       action='store_true', default=False, | 
|  | 26                       help="print grep commands to run and exit") | 
|  | 27     options, args = parser.parse_args(args) | 
|  | 28     if len(args) < 2: | 
|  | 29         parser.print_help() | 
|  | 30         parser.exit() | 
|  | 31     options.grep = options.grep or ['grep'] | 
|  | 32     pattern, directories = args[0], args[1:] | 
|  | 33 | 
|  | 34     # verify directories | 
|  | 35     missing = [i for i in directories | 
|  | 36               if not os.path.isdir(i)] | 
|  | 37     if missing: | 
|  | 38         sep = '\n  ' | 
|  | 39         parser.error("Not a directory:%s%s" % (sep, sep.join(missing))) | 
|  | 40 | 
|  | 41     # build command line | 
|  | 42     command = options.grep[:] | 
|  | 43     command.extend([pattern, options.files]) | 
|  | 44     cwd = os.getcwd() | 
|  | 45 | 
|  | 46     if options.print_commands: | 
|  | 47         # print grep commands | 
|  | 48         for directory in directories: | 
|  | 49             print "cd %s; %s" % (repr(directory), subprocess.list2cmdline(command)) | 
|  | 50         print "cd %s" % (repr(cwd)) | 
|  | 51         parser.exit() | 
|  | 52 | 
|  | 53     # loop through directories | 
|  | 54     for directory in directories: | 
|  | 55         print directory | 
|  | 56         subprocess.call(subprocess.list2cmdline(command), | 
|  | 57                         cwd=directory, | 
|  | 58                         shell=True) | 
|  | 59 | 
|  | 60 if __name__ == '__main__': | 
|  | 61     main() |