Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Env Variables in Python (v3.0) on Windows

I'm using Python 3.0.

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

Any help is much appreciated! Thanks!

like image 708
bitcycle Avatar asked Dec 06 '25 15:12

bitcycle


2 Answers

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.

like image 84
bobince Avatar answered Dec 08 '25 06:12

bobince


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')
like image 29
Jason Coon Avatar answered Dec 08 '25 04:12

Jason Coon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!