简体   繁体   中英

How to integrate a batch script that sets environment variables with a python script (3.7)?

I am running a python script that uses environment variables from a batch file. The variables are lost after the script is called. Here is an example of the code (example.py):

subprocess.Popen(env.cmd, shell=True).wait()

ENV_HOME = str(os.environ["ENV_HOME"])

I'm getting KeyError because ENV_HOME is not defined. I understand that I can use os.environ to set environment variables for my scripts to work, but env.cmd is a very large file that sets a lot of paths that I need for the python scripts to work. It's possible to read env.cmd into the python script, but since there are a lot of paths to set, I'm looking for an easier way to integrate the environment variables with the python script.

A workaround that I've been using is creating another cmd script:

call C:\Users\env.cmd

python example.py

ENV_HOME is defined if I use this process.

Environment variable set in child process are not available to the parent process - this is just the way the environment is designed. If you want to pass environment values from a child process to a parent, you need that child to output its environment (on standard output or in an agreed-upon file), using an agreed-upon format ( JSON or CSV would work well here), and then have the parent process that output, and set its environment accordingly.

As an aside, this is not a Python issue, and I have had to deal with similar issues in shell scripts I wrote in the past.

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