how to get the environment variable??

Mark Hadfield m.hadfield at niwa.cri.nz
Thu May 10 20:28:12 EDT 2001


From: <ed_tsang at yahoo.com>

> hi i am trying to set a global variable called tharn from the
> environemtn variable in my .cshrc file ...
> I used the folowing code:
> try:
>     tharn = os.environ['THARN']
> except KeyError:
>     try:
>        tharn = os.environ['CTF']
>     except KeyError:
>        print "\nEnvironment variable THARN must be set"
>        print "before starting the Test Harness."
>        sys.exit(1)
> The problem I am facing is tharn can be set by either environment
> varible CTF or THARN. Only one of CTF and THARN should  exist, or
> they can be both missing then user get a wanring message...

Seems to me the logic could be made clearer using the dictionary's "has_key"
method

if os.environ.has_key('THARN'):
    ...
elif os.environ.has_key('CTF'):
    ...
else
    print "Panic!"

This doesn't test for the possibility that both THARN and CTF exist, but
that probably doesn't matter & wouldn't be hard to do in any case.

---
Mark Hadfield
m.hadfield at niwa.cri.nz  http://katipo.niwa.cri.nz/~hadfield
National Institute for Water and Atmospheric Research



-- 
Posted from clam.niwa.cri.nz [202.36.29.1] 
via Mailgate.ORG Server - http://www.Mailgate.ORG



More information about the Python-list mailing list