PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, August 21, 2022

[FIXED] How to set environment variables with python?

 August 21, 2022     dotenv, environment-variables, python     No comments   

Issue

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.


Solution

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



Answered By - KZiovas
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing