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

Saturday, August 20, 2022

[FIXED] Why I have to use python-dotenv in order to load env variables to Python?

 August 20, 2022     environment-variables, python, python-3.x     No comments   

Issue

I am trying to read in a python script some variables that I have in an environment file myfile.env:

LOCALHOST='1'

If in my python script I just run:

import os
print(os.environ)

It prints:

environ({'PATH': '....', 'HOSTNAME': '...', 'PYCHARM_HOSTED': '1', 'PYTHONUNBUFFERED': '1'})

But in these array I don't have the LOCALHOST variable. I found that I can use python-dotenv and now I see it and working, but I don't get why I have to use it, and it's not feasible to load them only using os module.


Solution

Because a .env file is not the environment.

os.environ gets data from the environment which, somewhat oversimplified, is a string-to-string (name-to-value) mapping maintained by the operating system for each process, and inherited by child processes. Things are typically put there using export statements in a shell – they will then be inherited by all processes started from that shell — but there are other ways.

.env files are an application-level thing; the operating system does not know about them and they are not automatically loaded into the environment (and hence not picked up by os.environ). That is what python-dotenv takes care of for you.



Answered By - Ture Pålsson
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • 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