views:

113

answers:

2

Hello all. I'm using Python 3.0.

How to expand an environment variable given the %var_name% syntax?

Any help is much appreciated! Thanks!

+2  A: 

I'm guessing you mean "How do I get environment variables?":

import os
username = os.environ['UserName']

Alternatively, you can use:

username = os.getenv('UserName')

And to add/change your own variables, you can use:

os.putenv('MyVar', 'something I want to store')
jcoon
+3  A: 

It's in a slightly unexpected place: os.path.expandvars(). Admittedly it is quite often used for processing paths:

>>> import os.path
>>> os.path.expandvars('%APPDATA%\\MyApp')
'C:\\Documents and Settings\\Administrator\\Application Data\\MyApp'

but it's a shell function really.

bobince