Translating a Perl script into Python

Alex Martelli aleaxit at yahoo.com
Sat Jan 20 08:01:11 EST 2001


"Sheila King" <sheila at thinkspot.net> wrote in message
news:vo9i6t04nhurgv2avmgoss4mg86ofcuhtv at 4ax.com...
    [snip]
> qmail = ["SENDER", "NEWSENDER", "RECIPIENT", "USER", "HOME", "HOST",
"LOCAL",
>     "EXT", "EXT2", "EXT3", "EXT4", "DTLINE", "RPLINE", "UFLINE"]

Excellent, but perhaps closer to the original Perl might be

qmail = 'SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT EXT2 EXT3 \
    EXT4 DTLINE RPLINE UFLINE'.split()

> try:
> PROC = open("proc.test","w")
> except:
> sys.stderr << "Couldn't open file for write\n"
> raise

Perhaps better:

try: PROC = open('proc.test', 'w')
except: sys.exit(
    "Couldn't open file for write: %s" %
    traceback.format_exception_only(
    *sys.exc_info()[:2]))

or the "couldn't open" message could be lost in
the traceback; I don't think that message is all
that informative, so I'd just code
    PROC = open('proc.test', 'w')
and let normal exception processing tell me if
and why it couldn't open the file -- but if it IS
important to restate this fact, then the traceback
may then be undesirable.  Debatable, I guess.

> id = commands.getoutput("/usr/bin/id")
> PROC.write("ID: "+id+"\n\n")
> PROC.write("Environment Variables\n")
> for key in qmail:
> PROC.write(key + " = " + os.environ[key] + "\n")
> PROC.write("\nSlurp\n")
> for line in slurp:
> PROC.write(line)

These last two lines may be better expressed as
a single PROC.writelines(slurp).

> PROC.close()

I heartily approve the explicit closing of files, most
particularly ones you're writing; it's theoretically not
strictly necessary in today's Python, but I still think
it's a good idea.

> I appreciate all comments,

_excellent_ code, simple and effective; my comments
above are all about very marginal issues, because I
could not find anything substantial to criticize!-)


Alex






More information about the Python-list mailing list