Interface for modifying Windows environment variables from Python

后端 未结 6 1933
无人共我
无人共我 2020-12-08 05:01

How can I persistently modify the Windows environment variables from a Python script? (it\'s the setup.py script)

I\'m looking for a standard function or module to u

6条回答
  •  Happy的楠姐
    2020-12-08 06:06

    It may be just as easy to use the external Windows setx command:

    C:\>set NEWVAR
    Environment variable NEWVAR not defined
    
    C:\>python
    Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on
    win32
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import os
    >>> os.system('setx NEWVAR newvalue')
    0
    >>> os.getenv('NEWVAR')
    >>> ^Z
    
    
    C:\>set NEWVAR
    Environment variable NEWVAR not defined
    

    Now open a new Command Prompt:

    C:\>set NEWVAR
    NEWVAR=newvalue
    

    As you can see, setx neither sets the variable for the current session, nor for the parent process (the first Command Prompt). But it does set the variable persistently in the registry for future processes.

    I don't think there is a way of changing the parent process's environment at all (and if there is, I'd love to hear it!).

提交回复
热议问题