I'm using Python 3.0.
How to expand an environment variable given the %var_name% syntax?
Any help is much appreciated! Thanks!
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With