Search code examples
pythonwindowsenvironment-variablesenvironment

Can you set or delete an environment variable in python globally in windows?


I need to have an option to add and remove global environment variables on runtime from my python code, is it possible?


Solution

  • You can set it in the very first beginning of your program (top of the main file your execute):

    import os
    os.environ['ENV_VARIABLE_NAME'] = 'VALUE'
    

    but a better practice would be setting it outside of your application, e.g. if you have something running your app, then first use it to set the env variables, and then run your app.

    even if it's shell: export VAR=VALUE;python myapp.py...