pythonenvironment-variablespython-venv

Is there a way to automatically load environment variables when activating venv?


I am using python venv to create virtual environments. But, since I am working with several projects with different virtual environments, I don't want to manualy set environment variables every time I switch to a different project.

Is there a way to set venv environment variables automatically when activating the venv?

What is the best practice for this problem?


Solution

  • A good practice is to use dotenv. You can load your environment by placing your environment variables into a file named .env, and whenever you would like to load an environment, just use the lines:

    from dotenv import load_dotenv
    load_dotenv()
    

    This has the nicety that it only exists within the scope of you running a single script, since it essentially works like calling os.environ['variable'] = 'value' a number of times.