How to turn a variable name into a string?

Scott David Daniels Scott.Daniels at Acm.Org
Sat Mar 12 15:10:14 CET 2005


André Roberge wrote:
> stewart.midwinter at gmail.com wrote:
>> I have a number of variables (environmental variables, actually), most
>> of which will have a value. But some may not have been found by
>> os.environ.get(), so I set those to None. Now, if any of them are None,
>> the app cannot proceed, so I want to test for this and warn the user.
>> I could do something like this (actually, there are more than 3 vars):
>> a = "c:\\programs"
>> b = "d:\\data"
>> c = None  (result of an assignment after the os.environ.get() returned
>> a KeyError).
>> if (a is None) or (b is None) or (c is None):
>>     #do something here
>>     print 'you are missing some env vars'
>> But, that seemed clumsy to me, so I wanted to do something more
>> pythonic, hence my previous post.   So, any suggestions?

How about this:

     try:
         mumble = os.environ['TMP']
         babble = os.environ['Path']
         frobotz = os.environ['NotThere']
         jangle = int(os.environ['WEIGHT'])
         ...
     except KeyError, e:
         print 'Mising env var %r. Fix it and try again' % e.args
         raise SystemExit

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list