Translating a Perl script into Python

Sheila King sheila at spamcop.net
Sat Jan 20 17:40:07 EST 2001


Thanks to everyone for the comments. So far, I've tweaked the program a bit.
I'm pleased with how it's looking, now. But, I still have a question about the
whole "exception" issue, near the end of this post.

On Sat, 20 Jan 2001 05:57:03 GMT, Sheila King <sheila at thinkspot.net> wrote in
comp.lang.python in article <vo9i6t04nhurgv2avmgoss4mg86ofcuhtv at 4ax.com>:

:As part of my learning exercises, I've been attempting to translate a short
:perl script into Python.
...<snipped>...
:Here is the original Perl script:
:------------------------------------------------------------
:#!/usr/local/bin/perl
:
:@slurp = <>;
:@qmail = qw(SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT EXT2 EXT3
:EXT4 DTLINE RPLINE UFLINE);
:open PROC, ">proc.test" || die "Couldn't open file for write: $!";
:$id = `/usr/bin/id`;
:print PROC "ID: $id\n";
:print PROC "Environment Variables\n";
:foreach $key (@qmail) {
:  print PROC "$key = $ENV{$key}\n";
:}
:print PROC "\nSlurp\n";
:print PROC @slurp;
:close PROC;
:------------------------------------------------------------

Here is my new, improved Python version:

------------------------------------------------------------
#! /big/dom/xthinkspot/Python-2.0/python

import sys, os, commands, string

slurp = sys.stdin.read()
qmail = string.split("SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT EXT2
EXT3 EXT4 DTLINE RPLINE UFLINE")
PROC = open("proc.test","w")
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")
PROC.write(slurp)
PROC.close()
------------------------------------------------------------

I've tested in under both Python 1.5.1 and Python 2.0, so it works fine in
both versions.

And now for a question about exceptions:
I was searching the archives of the Tutor mailing list at Python.org and found
a message that addressed exactly this topic.

My understanding, now, of this situation (someone please confirm this):
Perl's "die" statement basically causes the program to exit.
Python, on trying to open the file, will throw an exception if the file is not
able to be opened, and the program will automatically halt (or "die") if I do
nothing to handle the exception. Also, it will print an appropriate error
message to stderr without my doing anything special to cause that.

If I wanted the program to not "die", I would have to handle the exception
somehow. The point is, this script is so short, and relies on the file being
opened when the script is invoked, if it cannot do so, the only appropriate
course of action at that point is to halt execution of the script.

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/






More information about the Python-list mailing list