Translating a Perl script into Python

Erno Kuusela erno-news at erno.iki.fi
Sat Jan 20 02:05:23 EST 2001


In article <vo9i6t04nhurgv2avmgoss4mg86ofcuhtv at 4ax.com>, Sheila King
<sheila at thinkspot.net> writes:

| 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:

it's usually a bad idea to have a blanket "except:" statement,
because it might mask other errors in your code.
in this case i'd use
  except (IOError, OSError), why:
        sys.exit('Couldn't write file: %s' % why)

sys.exit(), if supplied with a string, will print it to
stderr and exit with status 1.

| 	sys.stderr << "Couldn't open file for write\n"

fileobj << text doesn't work (python is not c++).

| 	raise

this will dump the traceback to the console in the event of an
error, it is probably not useful since you have reported the error
already.

| 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")

you can use the .get method of dictionaries if you want to supply
a default value in case the key is not found. you might want
to use it here (or you might not). it would be something like
os.environ.get(key, '(not set)')

| PROC.write("\nSlurp\n")
| for line in slurp:
| 	PROC.write(line)

line is a single string, not a list of lines since you used
read() and not readlines(). this loop will work, but it will
do the loop one character at a time which might be a bit slow.
you could do PROC.write(slurp).

| PROC.close()
| ------------------------------------------------------------

   -- erno



More information about the Python-list mailing list