how to get the environment variable??

Alex Martelli aleaxit at yahoo.com
Fri May 11 05:41:39 EDT 2001


<ed_tsang at yahoo.com> wrote in message
news:mailman.989535255.5071.python-list at python.org...
> 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...

What about using os.environ.get(name) -- that will return the
environment variable if set, else None, so you get to do all
the tests you desire.  E.g.:

def get_tharn():
    tharn_1 = os.environ.get('THARN')
    tharn_2 = os.environ.get('CTF')
    if tharn_1 is None:
        if tharn_2 is None:
            print "\nEnvironment variable THARN or CTF must be"
            print "set before starting the Test Harness."
            sys.exit(1)
        return tharn_2
    else:
        if tharn_2 is not None:
            print "\nOnly one of environment variables THARN
            print "or CTF should be set, not both"
            # should we exit here...?
        return tharn_1

If you have many similar cases, where a value should be
provided by one, and only one, of several possible
environment values, you may want to generalize this
pattern into a function taking as arguments the variable
names to be checked.  The two error cases (no variable
is set, more than one variable is set) may be diagnosed
by raising appropriate exceptions, or lead to error or
warning messages automatically.  An example of the latter:

def oneOfEnv(*names):
    number_set = 0
    for name in names:
        value = os.environ.get(name)
        if value is not None:
            result = value
            number_set += 1
    if number_set > 1:
        print "\nOnly one of environment variables",
        for name in names: print name,
        print "\nshould be set,",number_set,"were"
        return result
    elif number_set == 0:
        print "\nOne of environment variables",
        for name in names: print name,
        print "\nshould be set before running the test harness"
        sys.exit(1)
    return result

Now calling
    tharn = oneOfEnv('THARN','CTF')
will supply the result you need here, and the code is
reusable for other similar cases.


Alex






More information about the Python-list mailing list