Translate Perl to Python: do it or die

I am moving Perl (from which I have very little knowledge) a script in python.

$path = $ENV{ 'SOME_NAME' } || die " SOME_NAME ENV VARIABLE NOT FOUND\n"; 

I can (hopefully) see what this line does, either set the variable "path" to the environment variable "SOME_NAME", or not execute it, and then print the error message to the user. (Note: does anyone know how to get a search engine to search for special characters such as "||"?)

I tried to implement it in a "pythonic" way (it’s easier to ask for forgiveness than permission) using:

 try: path = os.environ['SOME_NAME'] except KeyError,e: print "SOME_NAME ENVIRONMENT VARIABLE NOT FOUND\n" raise e 

but it seems rather cumbersome, especially since I do it for three different environment variables.

Any ideas if there is a more efficient implementation, or would you say that this is a "pythonic" way to do this?

Many thanks

+8
python perl
source share
2 answers
 try: path = os.environ['SOME_NAME'] var2 = os.environ['VAR2'] var3 = os.environ['VAR3'] var4 = os.environ['VAR4'] except KeyError,e: print "Not found: ", e 

You can put several statements in a try block.

+11
source share

What you have is actually a fairly common idiom, and perhaps a preferred template. Or you just simply throw a normal exception without printing anything extra. Python initially has the same effect. Thus,

 path = os.environ["SOME_NAME"] 

It simply throws a KeyError exception on its own, and the default behavior is to exit uncaught exceptions. The trail will show you what and where.

However, you can also specify a default value if possible.

 path = os.environ.get("SOME_NAME", "/default/value") 

This will not cause an error, and you can do something as reasonable as the default action.

+6
source share

All Articles