Re: quickie filters

Guido van Rossum (Guido.van.Rossum@cwi.nl)
Tue, 07 Jul 1992 10:11:48 +0200

>In perl there are flags to:
>
> a. read the program from the command line

Python has this too -- it's called '-c commands' in analogy with *sh.

> b. iterate over all the arguments using them as successive
> input files
>
> c. automatically split each input line
>
>This makes it easy to write quickie filters.
[examples omitted]

Remember that this works with Perl because many other features of the
language are designed to cooperate, e.g. the defaults for regexp
matching etc. Frankly, I'd rather not try to compete with Perl in the
areas where Perl is best -- it's a battle that's impossible to win,
and I don't think it is a good idea to strive for the number of
obscure options and shortcuts that Perl has acquired through the year.
If you want Perl, use it -- Python wins where you need sophisticated
data structures or object-orientation.

On the other hand, it isn't hard to write a Python script that
emulates these options. Here's a simple one that emulates -ae:

------------------------------------------------------------------------
#! /usr/local/python

# Wrapper around Python to emulate the Perl -ae options:
# (1) first argument is a Python command
# (2) rest of arguments are input files (default or '-': read stdin)
# (3) each line is put into the string L with trailing '\n' stripped
# (4) the fields of the line are put in the list F
# (5) also: FILE: full filename; LINE: full line; FP: open file object

import sys
import string

command = sys.argv[1]

if not sys.argv[2:]:
sys.argv[2:] = ['-']

for FILE in sys.argv[2:]:
if FILE == '-':
FP = sys.stdin
else:
FP = open(FILE, 'r')
while 1:
LINE = FP.readline()
if not LINE: break
L = LINE[:-1]
F = string.split(L)
exec(command)
------------------------------------------------------------------------

This version is inefficient because it parses and "compiles" the
command for each input line, but it is possible to solve that by
creative use of exec(). You can also imagine more useful handling of
missing input files, syntax errors in the script, etc.

--Guido van Rossum, CWI, Amsterdam <guido@cwi.nl>
"Well I'm a plumber. I can't act"