Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read Windows environment variable value?

I tried this:

os.environ['MyVar'] 

But it did not work! Is there any way suitable for all operating systems?

like image 365
Ahmad Soboh Avatar asked May 08 '12 10:05

Ahmad Soboh


People also ask

How do I find the value of an environment variable in Windows?

On the Windows taskbar, right-click the Windows icon and select System. In the Settings window, under Related Settings, click Advanced system settings. On the Advanced tab, click Environment Variables.

How do I find the value of an environment variable?

To display the values of environment variables, use the printenv command. If you specify the Name parameter, the system only prints the value associated with the variable you requested.

How do I read an environment variable in PowerShell?

Environment variables in PowerShell are stored as PS drive (Env: ). To retrieve all the environment variables stored in the OS you can use the below command. You can also use dir env: command to retrieve all environment variables and values.

Which is used to read environment variable?

The command env displays all environment variables and their values.


1 Answers

Try using the following:

os.getenv('MyVar') 

From the documentation:

os.getenv(varname[, value])

Return the value of the environment variable varname if it exists, or value if it doesn’t. value defaults to None.

Availability: most flavors of Unix, Windows

So after testing it:

>>> import os >>> os.environ['MyVar'] = 'Hello World!'       # set the environment variable 'MyVar' to contain 'Hello World!' >>> print os.getenv('MyVar') Hello World! >>> print os.getenv('not_existing_variable') None >>> print os.getenv('not_existing_variable', 'that variable does not exist') that variable does not exist >>> print os.environ['MyVar'] Hello World! >>> print os.environ['not_existing_variable'] Traceback (most recent call last):   File "<stdin>", line 1, in ?   File "/usr/lib/python2.4/UserDict.py", line 17, in __getitem__     def __getitem__(self, key): return self.data[key] KeyError: 'not_existing_variable     

Your method would work too if the environmental variable exists. The difference with using os.getenv is that it returns None (or the given value), while os.environ['MyValue'] gives a KeyError exception when the variable does not exist.

like image 148
Niek de Klein Avatar answered Sep 30 '22 18:09

Niek de Klein