如何集成设置环境变量的批处理脚本和python脚本(3.7)? [英] How to integrate a batch script that sets environment variables with a python script (3.7)?

查看:73
本文介绍了如何集成设置环境变量的批处理脚本和python脚本(3.7)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个使用批处理文件中的环境变量的python脚本.调用脚本后,变量将丢失.这是代码示例(example.py):

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"])

我收到KeyError,因为未定义ENV_HOME.我了解可以使用os.environ设置环境变量以使脚本正常工作,但是env.cmd是一个非常大的文件,它设置了许多python脚本正常工作所需的路径.可以将env.cmd读取到python脚本中,但是由于要设置的路径很多,我正在寻找一种将环境变量与python脚本集成的简便方法.

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.

我一直在使用的解决方法是创建另一个cmd脚本:

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

call C:\Users\env.cmd

python example.py

如果使用此过程,则定义

ENV_HOME.

ENV_HOME is defined if I use this process.

推荐答案

子进程中设置的环境变量不适用于父进程-这只是设计环境的方式.如果要将环境值从子进程传递给父进程,则需要该子进程使用协议格式( JSON )输出其环境(在标准输出或协议文件中).>或 CSV 在这里效果很好),然后让父进程输出,并相应地设置其环境.

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.

顺便说一句,这不是Python问题,我不得不在过去编写的shell脚本中处理类似的问题.

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.

这篇关于如何集成设置环境变量的批处理脚本和python脚本(3.7)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆