Reputation: 81
Here is what I want to achieve: I am coding a Python based software, which will need to append new directories to PATH in environment variables in Windows. In order to do that, I first get the path, then modify the string, and last use SETX to update the new PATH.
My problem: I tried three methods to get PATH (with python or cmd), but they all returns me the combination of USER PATH and SYSTEM PATH. The three methods are:
os.environ['PATH']
os.system('echo %PATH%')
os.system('set PATH')
I cannot accept the combination of user path and system path, because this would result in new user PATH being too long, and being truncated to 1024 characters (limitation by Microsoft). I have read a post with the exact same problem. The problem seems to be solved by using Registry in that case: http://stackoverflow.com/questions/13359082/windows-batch-select-only-user-variables. The solution suggest using
reg query HKCU\Environment /v PATH
to access registry where the user variables and system variables are separated. But the solution does not work for me. When I run it on commend line, it returns me "Access is denied". As a result, I am looking for method that return only user Path in environment variables without access to Registry. Thank you.
Upvotes: 3
Views: 1044
Reputation: 81
import _winreg
import unicodedata
keyQ = _winreg.OpenKey(_winreg.HKEY_CURRENT_USER, 'Environment', 0, _winreg.KEY_QUERY_VALUE)
path_old, _ = _winreg.QueryValueEx(keyQ, "PATH")
#the result is unicode, need to be converted
unicodedata.normalize('NFKD', path_old).encode('ascii','ignore')
Although I said I want an answer without access to registry, it turns out this is the only way to get user environment variable "PATH". Thank you everyone.
Upvotes: 2