0

I thought of using the following to run a normally-run-as-shell inside python:

x = subprocess.call('source credentials.txt', shell=True)
print os.environ

However, it seems that the environment doesn't update in the rest of the script. Why not? And is there a way to get over this with using shell (and not python) to update my os vars?

2 Answers 2

1

Take a look at this library: https://pypi.org/project/python-dotenv/

I've used it before and it's simple and does the job.Instead of 'credentials.txt' you put the key-value pairs in '.env' file and load it during program start using a single 'load' call.

Here is somple code:

import os
from pathlib import Path
from dotenv import load_dotenv, find_dotenv

# write some sample contents in the current dir
Path.cwd().joinpath(".env").write_text("USERNAME=My user name\nPASSWORD=MyCust0mS3cr3tPAsw00d")

# loads from .env file in CWD
load_dotenv(find_dotenv())  

# here is the magic:
print(os.environ["PASSWORD"])
Sign up to request clarification or add additional context in comments.

1 Comment

It seems that I had miss-understood the quesiton and you try to go the other way arround - push the variables to the outside world, but my answer is still good if you are just trying to pass variables between python programs - just keep them at known location and reload frequently from there. This way you won't pollute the global system vars and reduce the risk of your credentials being stolen.
0

You can run a subprocess to source the results and print the os.environ back to the current python process. For example:

os.environ=ast.literal_eval(subprocess.check_output(
  'source credentials.txt && python -c "import os;print os.environ"', shell=True)
)

Answer inspired by this answer.

Comments

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.