How to set environment variables in Python?

In Python, you can set environment variables using the os module. Here is an example code snippet that sets the environment variable "MY_VARIABLE" to the value "hello":

import os

# Set the environment variable
os.environ['MY_VARIABLE'] = 'hello'

# Access the environment variable
print(os.environ['MY_VARIABLE'])

Watch a course Python - The Practical Guide

You can also use os.environ.update() method to set multiple variables at once:

import os

# Set the environment variable
os.environ.update({'MY_VARIABLE_1': 'hello', 'MY_VARIABLE_2': 'world'})

# Access the environment variable
print(os.environ['MY_VARIABLE_1'])
print(os.environ['MY_VARIABLE_2'])

Please note that the changes made to the environment variables using os.environ will only be effective in the current process and its child processes, and will not affect the environment of the parent process that started the Python script.

It's also worth mentioning that you can use os.environ.get() method to access the variable value, it will return None if the variable is not set in the environment.