5

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')
5
  • 1
    stackoverflow.com/questions/4906977/… Commented May 31, 2016 at 12:58
  • 1
    Possible duplicate of stackoverflow.com/questions/4906977/… Commented May 31, 2016 at 13:00
  • 1
    You're limited to the environment variables restricted by your current user level. Meaning you need to run as administrator go get certain paths, some paths are only local to the user. Commented May 31, 2016 at 13:00
  • Dear iHowell, at your link I do not find the answer. Commented May 31, 2016 at 13:03
  • Dear Torxed, I think your comment could be the answer :( Commented May 31, 2016 at 13:05

1 Answer 1

3

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]
Sign up to request clarification or add additional context in comments.

7 Comments

It is not true that 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.
I run the 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.
Which variables do you get? Are they the same as the user variables in 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.
Yes, with 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)
Running python.exe as a child of cmd.exe should inherit the exact same PATH value that you see in cmd.exe via set PATH.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.