How to set environment variables in Python?

前端 未结 11 1749
情话喂你
情话喂你 2020-11-22 04:00

I need to set some environment variables in the Python script and I want all the other scripts that are called from Python to see the environment variables\' set.

If

11条回答
  •  [愿得一人]
    2020-11-22 04:18

    You can use the os.environ dictionary to access your environment variables.

    Now, a problem I had is that if I tried to use os.system to run a batch file that sets your environment variables (using the SET command in a **.bat* file) it would not really set them for your python environment (but for the child process that is created with the os.system function). To actually get the variables set in the python environment, I use this script:

    import re
    import system
    import os
    
    def setEnvBat(batFilePath, verbose = False):
        SetEnvPattern = re.compile("set (\w+)(?:=)(.*)$", re.MULTILINE)
        SetEnvFile = open(batFilePath, "r")
        SetEnvText = SetEnvFile.read()
        SetEnvMatchList = re.findall(SetEnvPattern, SetEnvText)
    
        for SetEnvMatch in SetEnvMatchList:
            VarName=SetEnvMatch[0]
            VarValue=SetEnvMatch[1]
            if verbose:
                print "%s=%s"%(VarName,VarValue)
            os.environ[VarName]=VarValue
    

提交回复
热议问题