1

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Great thanks, and using docker, and setting env_file parameter doesnt load that file to the os.environment?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.