How to set environment variables in Python?

前端 未结 11 2026
情话喂你
情话喂你 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:16

    I have been trying to add environment variables. My goal was to store some user information to system variables such that I can use those variables for future solutions, as an alternative to config files. However, the method described in the code below did not help me at all.

    import os
    os.environ["variable_1"] = "value_1"
    os.environ["variable_2"] = "value_2"
    # To Verify above code
    os.environ.get("variable_1")
    os.environ.get("variable_2")
    

    This simple code block works well, however, these variables exist inside the respective processes such that you will not find them in the environment variables tab of windows system settings. Pretty much above code did not serve my purpose. This problem is discussed here: variable save problem

    os.environ.putenv(key, value)
    

    Another unsuccessful attempt. So, finally, I managed to save variable successfully inside the window environment register by mimicking the windows shell commands wrapped inside the system class of os package. The following code describes this successful attempt.

    os.system("SETX {0} {1} /M".format(key, value))
    

    I hope this will be helpful for some of you.

提交回复
热议问题