How can I get system environment variables on Windows? With the below code I only get the user environment variables:
os.environ['PATH']
Or this returns the same:
os.getenv('PATH')
How can I get system environment variables on Windows? With the below code I only get the user environment variables:
os.environ['PATH']
Or this returns the same:
os.getenv('PATH')
Based on a (deleted) comment I found the solution. System environment variables should be read from the registry if the Python script is run by a user and not by administrator.
import winreg
reg_path = r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'
reg_key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, reg_path)
system_environment_variables = winreg.QueryValueEx(reg_key, 'Path')[0]
os.environ['PATH'] only returns the user PATH. When you log on with a loaded profile, your user PATH is appended to the system PATH, which is inherited by Explorer and all of its child processes.os.environ['PATH'] on my Win7 x64 with my user, and I got only the user environment variables. I don't know what I'm doing wrong, but my user PATH has only 3 variables, and my system PATH has more than 30, and python returns only with the 3. In python I was not able to run external commands via subprocess because python does not see the system PATH. So I had to read the registry for the system PATH and set this explicitly at subprocess.Popen(). So now I can run my commands.HKEY_CURRENT_USER\Environment? If cmd.exe is run with an empty environment, it sets 3 default variables: COMSPEC, PATHEXT, and PROMPT. The default values have nothing to do with the user's environment variables.os.environ['PATH'] I get the HKEY_CURRENT_USER\Environment. If I open cmd.exe in Windows then I can use every executable regarding to system PATH (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment)PATH value that you see in cmd.exe via set PATH.