1 #! /usr/local/bin/python
3 # Emulate some Perl command line options.
4 # Usage: pp [-a] [-c] [-d] [-e scriptline] [-F fieldsep] [-n] [-p] [file] ...
5 # Where the options mean the following:
6 # -a : together with -n or -p, splits each line into list F
7 # -c : check syntax only, do not execute any code
8 # -d : run the script under the debugger, pdb
9 # -e scriptline : gives one line of the Python script; may be repeated
10 # -F fieldsep : sets the field separator for the -a option [not in Perl]
11 # -n : runs the script for each line of input
12 # -p : prints the line after the script has run
13 # When no script lines have been passed, the first file argument
14 # contains the script. With -n or -p, the remaining arguments are
15 # read as input to the script, line by line. If a file is '-'
16 # or missing, standard input is read.
19 # - add -i extension option (change files in place)
20 # - make a single loop over the files and lines (changes effect of 'break')?
21 # - add an option to specify the record separator
22 # - except for -n/-p, run directly from the file if at all possible
37 optlist
, ARGS
= getopt
.getopt(sys
.argv
[1:], 'acde:F:np')
38 except getopt
.error
, msg
:
39 sys
.stderr
.write(sys
.argv
[0] + ': ' + msg
+ '\n')
42 for option
, optarg
in optlist
:
50 for line
in string
.splitfields(optarg
, '\n'):
61 print option
, 'not recognized???'
63 if not ARGS
: ARGS
.append('-')
69 fp
= open(ARGS
[0], 'r')
73 SCRIPT
.append(line
[:-1])
76 if not ARGS
: ARGS
.append('-')
82 # Note that it is on purpose that AFLAG and PFLAG are
83 # tested dynamically each time through the loop
86 'for FILE in ARGS:', \
87 ' \tif FILE == \'-\':', \
88 ' \t \tFP = sys.stdin', \
90 ' \t \tFP = open(FILE, \'r\')', \
93 ' \t \tLINE = FP.readline()', \
94 ' \t \tif not LINE: break', \
95 ' \t \tLINENO = LINENO + 1', \
96 ' \t \tLINECOUNT = LINECOUNT + 1', \
97 ' \t \tL = LINE[:-1]', \
98 ' \t \taflag = AFLAG', \
100 ' \t \t \tif FS: F = string.splitfields(L, FS)', \
101 ' \t \t \telse: F = string.split(L)' \
104 ' \t \tif not PFLAG: continue', \
106 ' \t \t \tif FS: print string.joinfields(F, FS)', \
107 ' \t \t \telse: print string.join(F)', \
108 ' \t \telse: print L', \
114 # Note that we indent using tabs only, so that any indentation style
115 # used in 'command' will come out right after re-indentation.
117 program
= string
.joinfields(prologue
, '\n') + '\n'
119 program
= program
+ (' \t \t' + line
+ '\n')
120 program
= program
+ (string
.joinfields(epilogue
, '\n') + '\n')
123 tfn
= tempfile
.mktemp()
130 pdb
.run('execfile(' + `tfn`
+ ')')