Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set environment variables with python?

I wish to read an .env file with python and expose the environment variables so they can be accessed by other scripts in the same environment. I have this script :

from dotenv import load_dotenv
import os

load_dotenv("common.env")
print(os.environ["CONFIG_FOLDER_NAME"])

When I run this script it prints the correct value.

However when I try to read the variables from a different file they don't seem to exist. Even if I do echo $CONFIG_FOLDER_NAME it return empty.

like image 331
KZiovas Avatar asked Nov 20 '25 20:11

KZiovas


1 Answers

Ok so based on the comment above, to help future users who might not be aware of this, you cannot set environment variables outside the scope of the current process with Python.

You can make python aware of some variables and change env variables for the scope of a process and its child processes. But you can not set values for env in the system itself or other processes (that are not children of the current process). For example if I set a env variable called HOST_URL it wont be actually accessible in the system environment.

I found three ways to actually set the variables by:

  1. Running a bash script to set the env variable values
  2. Use VSCode launch.json for setting the variables either with env or envFile
  3. Define them through Docker file or docker-compose.yml if you are containerizing your app

Note: If there are other options to address this please comment and I ll add them. I want this to be a helpfull post for new developers like myself. Shaming and non-helpful comments never helped anyone or improved anything. This is, or should be, a learning and knowledge exchange platform and it should be open to all programming questions Stack Overflow Isn’t Very Welcoming. It’s Time for That to Change

like image 142
KZiovas Avatar answered Nov 22 '25 09:11

KZiovas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!