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?

David542
  • 104,438
  • 178
  • 489
  • 842

2 Answers2

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"])
Hrisimir Dakov
  • 557
  • 3
  • 9
  • 1
    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. – Hrisimir Dakov Mar 01 '20 at 01:32
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.

David542
  • 104,438
  • 178
  • 489
  • 842