Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translate Perl to Python: do this or die

Tags:

python

perl

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

like image 847
Jdog Avatar asked Aug 12 '11 11:08

Jdog


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

like image 128
Jacob Avatar answered Oct 05 '22 09:10

Jacob