0

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.

1
  • you can set environment variable through batch or shell script. Commented May 12, 2020 at 16:04

1 Answer 1

0

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.

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

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.