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 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/