Guido van Rossum | ca7b213 | 1992-07-07 09:11:53 +0000 | [diff] [blame^] | 1 | #! /usr/local/python |
| 2 | |
| 3 | # Wrapper around Python to emulate the Perl -ae options: |
| 4 | # (1) first argument is a Python command |
| 5 | # (2) rest of arguments are input to the command in an implied loop |
| 6 | # (3) each line is put into the string L with trailing '\n' stripped |
| 7 | # (4) the fields of the line are put in the list F |
| 8 | # (5) also: FILE: full filename; LINE: full line; FP: open file object |
| 9 | # The command line option "-f FS" sets the field separator; |
| 10 | # this is available to the program as FS. |
| 11 | |
| 12 | import sys |
| 13 | import string |
| 14 | import getopt |
| 15 | |
| 16 | FS = '' |
| 17 | |
| 18 | optlist, args = getopt.getopt(sys.argv[1:], 'f:') |
| 19 | for option, optarg in optlist: |
| 20 | if option == '-f': FS = optarg |
| 21 | |
| 22 | command = args[0] |
| 23 | |
| 24 | if not args[1:]: args.append('-') |
| 25 | |
| 26 | prologue = [ \ |
| 27 | 'for FILE in args[1:]:', \ |
| 28 | '\tif FILE == \'-\':', \ |
| 29 | '\t\tFP = sys.stdin', \ |
| 30 | '\telse:', \ |
| 31 | '\t\tFP = open(FILE, \'r\')', \ |
| 32 | '\twhile 1:', \ |
| 33 | '\t\tLINE = FP.readline()', \ |
| 34 | '\t\tif not LINE: break', \ |
| 35 | '\t\tL = LINE[:-1]', \ |
| 36 | '\t\tif FS: F = string.splitfields(L, FS)', \ |
| 37 | '\t\telse: F = string.split(L)' \ |
| 38 | ] |
| 39 | |
| 40 | # Note that we indent using tabs only, so that any indentation style |
| 41 | # used in 'command' will come out right after re-indentation. |
| 42 | |
| 43 | program = string.joinfields(prologue, '\n') |
| 44 | for line in string.splitfields(command, '\n'): |
| 45 | program = program + ('\n\t\t' + line) |
| 46 | program = program + '\n' |
| 47 | |
| 48 | exec(program) |