简体   繁体   中英

set virtual environment variable while script runs?

I'd like to save my credentials in a file (config_vars.env) which is gitignored. Then I'd like to start my project and have those credentials set to environment variables because my program uses os.environ.get('DB_NAME') and the like.

So I'd like those environment variables to be set while my script runs, then deleted when my program stops running.

I could literally set them using python or bash, then unset them upon exit. But that's not ideal because if my program crashes the environment variables are left there.

Ideally, I'd be able to automatically set them in a virtual environment, only available to my process, and when the process stops running the env vars are gone.

Is there any way to do this in native python? I've looked into things like click or dotenv for python, but is there no other way?

Here's what I've got so far:

import os
import subprocess

def bash_command():

    #not good
    #subprocess.Popen(cmd, shell=False, executable=".\git-bash.exe")
    #os.popen('setenv a b')

    subprocess.call("config_vars.sh", shell=False)
    print(os.environ.get('DB_NAME')) # prints None because the env var dies with bash
    import time
    time.sleep(5) # delays for 5 seconds

bash_command()

and config_vars.sh is:

export ENV_FILE=env/config_vars.env
echo $DB_NAME

That echo command shows that it worked, but the bash process ends, removing that environment variable (or the whole virtual environment altogether) and the python process continues without having access to it.

So the question is: How can I set environment variables that die when my python process dies?

You have to capture the output of the script; the child cannot affect the parent's environment, so you need some form of interprocess communication.

value = subprocess.check_output("config_vars.sh", shell=False).lstrip('\n')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM