How to set environment variables in Python?

How to set environment variables in Python?

You can set an environment variable in Python using the os module. To set a variable named DEBUSSY to the string 1, use os.environ["DEBUSSY"] = "1". Later, to access this variable, simply use print(os.environ["DEBUSSY"]).

Remember that child processes inherit the environment of the parent process automatically, so no additional steps are needed to access this variable in child processes.

Try using os.environ.setdefault() method that sets the environment variable MY_VAR to my_value if it is not already set.

 import os
os.environ.setdefault("MY_VAR", "my_value")

Use dotenv package which is useful for managing environment variables in development environments without exposing them in version control.

First, install the package using pip:

pip install python-dotenv

Then, create a .env file in your project directory:

MY_VAR=my_value

In your Python code, load the environment variables from the .env file:

from dotenv import load_dotenv
import os

load_dotenv()  # Load environment variables from .env file
my_var = os.getenv("MY_VAR")