Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Access environment variable values in Python

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variable in Python’s we can use os module which provides a property called environ that contains environment variables in key-value pairs. These are the different ways of accessing environment variables:

Access all environment variables using os.environ

Here, we are accessing all the environment variables that are present in the environment.

Python3




# import os module
import os
  
# display all environment variable
print(os.environ)

Output:

Access environment variable values in Python

 

Access single environment variable using os.environ

Here, we are extracting single environment variable of COMPUTERNAME from the above list. If we try to access an environment variable that is not available we will get KeyError.

Python3




# import os module
import os
  
# access environment variable
print(os.environ['COMPUTERNAME'])

Output:

DESKTOP-M2ASD91

Get value of the environment variable key using os.environ

Here, we are extracting single environment variable key of USERPROFILE path from the environ list. This will return None if the given key is not found.

Python3




# import os module
import os
  
# access environment variable using the key
print(os.environ.get('USERPROFILE'))

Output:

C:\Users\suraj

Return default value if the key doesn’t exist

Python3




# import os module
import os
  
# return default value if no 
# key/environment variable if found
print(os.environ.get('DATABASE_NAME', 'example.database.net'))

Output:

example.database.net/

My Personal Notes arrow_drop_up
Last Updated : 07 Nov, 2022
Like Article
Save Article
Similar Reads
Related Tutorials