Tutorials  Articles  Notifications  Login  Signup


AS

Anoop Singh

SDE 1 at Amazon March 31, 2020, 12:10 a.m. ⋅ 966 views

Accessing environment variable values in Python


There might be times, when we want to access environment variables of system that our program is running on.

To access environment variable values in Python we can use os.environ

import os
print(os.environ)

This will give you all the environment virables of system inlcuding a lot of other details like, username and path etc.

To get a specific value from environment variable you can pass it to os.environ.

import os
print(os.environ['TMP'])

This wll give you path of Temp directory on windows machine. 

If the key is not available in environment variables it will throw en error. 

You can get some default value.

print(os.getenv('SOME_KEY', default_value))

 

To find out where is path of python installation, you can use sys.prefix

import sys
print(sys.prefix)

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account