Jdog
Jdog

Reputation: 10721

Translate Perl to Python: do this or die

I am moving a Perl (of which I have very little knowledge) script to 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 failing that then print an error message to the user. (Side note: anyone know how to get a search engine to search for special characters like '||'?)

I've tried to implement it in a "pythonic" way (Easier to Ask Forgiveness than Permission) using:

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

but this seems rather cumbersome, especially as I'm doing it for 3 different environment variables.

Any ideas if there is a better implementation or would you say this is the "pythonic" way to go about it?

Many Thanks

Upvotes: 9

Views: 1631

Answers (2)

Keith
Keith

Reputation: 43024

What you have there is actually pretty common idiom, and arguably the preferred pattern. Or you just just let the normal exception pass without printing anything extra. Python natively has the same effect. So,

path = os.environ["SOME_NAME"]

Will just raise a KeyError exception all by itself and the default behavior is to exit on uncaught exceptions. The traceback will show you what and where.

However, you can also provide a default value, if that's possible.

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

This will not raise an error and you may do something sensible as a default action.

Upvotes: 6

Jacob
Jacob

Reputation: 43229

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 more than one statement into a try block.

Upvotes: 11

Related Questions