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

£可爱£侵袭症+ 提交于 2021-01-29 10:18:49

问题


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:


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.



来源:https://stackoverflow.com/questions/61755986/how-to-integrate-a-batch-script-that-sets-environment-variables-with-a-python-sc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!