Translating a Perl script into Python

Sheila King sheila at thinkspot.net
Sat Jan 20 00:57:03 EST 2001


As part of my learning exercises, I've been attempting to translate a short
perl script into Python.

I don't really know Perl, but when I was attempting to learn how to use the
.qmail files at my web host and run scripts on it for filtering, etc... the
sysadmin posted a sample script in Perl to give me an idea what some of the
possibilities might be.

I think I understand the Perl script well enough to try to translate it. So,
here I will present the two scripts: (1) The original Perl script written by
the sysadmin at my web host, and (2) my attempt at a Python translation. I've
already tested it, and the output files are identical. I'm curious about style
or good programming type comments.

Note: the identifiers SENDER NEWSENDER RECIPIENT USER HOME HOST LOCAL EXT EXT2
EXT3 EXT4 DTLINE RPLINE UFLINE
are environment variables passed by .qmail to the script.

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 Python translation:
------------------------------------------------------------
#! /big/dom/xthinkspot/Python-2.0/python

import sys, os, commands

slurp = sys.stdin.read()
qmail = ["SENDER", "NEWSENDER", "RECIPIENT", "USER", "HOME", "HOST", "LOCAL",
"EXT", "EXT2", "EXT3", "EXT4", "DTLINE", "RPLINE", "UFLINE"]
try:
	PROC = open("proc.test","w")
except:
	sys.stderr << "Couldn't open file for write\n"
	raise
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)
PROC.close()
------------------------------------------------------------

I appreciate all comments,

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




More information about the Python-list mailing list