Reading in NT Variables / Login Script

Bengt Richter bokr at oz.net
Thu Jun 5 12:29:12 EDT 2003


On 5 Jun 2003 01:45:13 -0700, tony at pc-tony.com (Tony) wrote:

>c42 <nospam at nospam.net> wrote in message news:<MPG.1947a861dc883f29989680 at news2.atlantic.net>...
>> What variables are you looking for?
>> 
>%USERNAME% in particualr.  But others would be useful.
>
os.environ acts like a case-insensitive dictionary of environment variables

 >>> import os
 >>> os.environ.get('username', '(username unknown)')
 'bokr'
 >>> os.environ['username']
 'bokr'
 >>> os.environ['USERNAME']
 'bokr'
 >>> os.environ.get('USERNAME', '(username unknown)')
 'bokr'
 >>> os.environ['USERNAME']
 'bokr'
 >>> os.environ['PATHEXT']
 '.COM;.EXE;.BAT;.CMD'
 >>> os.environ['prompt']
 '[$T$H$H$H$H$H$H] $P$G'
 >>> os.environ['FOO']
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "D:\python22\lib\os.py", line 379, in __getitem__
     return self.data[key.upper()]
 KeyError: FOO

(You can see how the case-insensitivity came about)

Using .get avoids an exception if the environment variable is not defined:

 >>> os.environ.get('foo', "default doesn't have to be a string".split())
 ['default', "doesn't", 'have', 'to', 'be', 'a', 'string']

HTH

Regards,
Bengt Richter




More information about the Python-list mailing list