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
36 optlist
, ARGS
= getopt
.getopt(sys
.argv
[1:], 'acde:F:np')
37 except getopt
.error
, msg
:
38 sys
.stderr
.write('%s: %s\n' % (sys
.argv
[0], msg
))
41 for option
, optarg
in optlist
:
49 for line
in optarg
.split('\n'):
60 print option
, 'not recognized???'
62 if not ARGS
: ARGS
.append('-')
68 fp
= open(ARGS
[0], 'r')
72 SCRIPT
.append(line
[:-1])
75 if not ARGS
: ARGS
.append('-')
81 # Note that it is on purpose that AFLAG and PFLAG are
82 # tested dynamically each time through the loop
86 ' \tif FILE == \'-\':',
87 ' \t \tFP = sys.stdin',
89 ' \t \tFP = open(FILE, \'r\')',
92 ' \t \tLINE = FP.readline()',
93 ' \t \tif not LINE: break',
94 ' \t \tLINENO = LINENO + 1',
95 ' \t \tLINECOUNT = LINECOUNT + 1',
96 ' \t \tL = LINE[:-1]',
97 ' \t \taflag = AFLAG',
99 ' \t \t \tif FS: F = L.split(FS)',
100 ' \t \t \telse: F = L.split()'
103 ' \t \tif not PFLAG: continue',
105 ' \t \t \tif FS: print FS.join(F)',
106 ' \t \t \telse: print \' \'.join(F)',
107 ' \t \telse: print L',
113 # Note that we indent using tabs only, so that any indentation style
114 # used in 'command' will come out right after re-indentation.
116 program
= '\n'.join(prologue
) + '\n'
118 program
+= ' \t \t' + line
+ '\n'
119 program
+= '\n'.join(epilogue
) + '\n'
122 fp
= tempfile
.NamedTemporaryFile()
127 pdb
.run('execfile(%r)' % (fp
.name
,))