How can I access environment variables in Python?
You can use the os
module in Python to access environment variables. Here's an example:
import os
# Access an environment variable
value = os.environ['VAR_NAME']
# Set an environment variable
os.environ['VAR_NAME'] = 'new value'
Watch a video course
Python - The Practical Guide
You can also use the os.getenv()
function to get the value of an environment variable. This function takes the name of the environment variable as a string argument and returns the value as a string. If the specified environment variable does not exist, it returns None
.
import os
# Get the value of an environment variable
value = os.getenv('VAR_NAME')
# Set a default value if the environment variable does not exist
value = os.getenv('VAR_NAME', 'default value')
Keep in mind that changes made to the environment variables using the os
module are not permanent and are only valid for the current session. If you want to make permanent changes to the environment variables, you will need to modify the system's environment variables.