简体   繁体   English

如何在不访问Registry的情况下仅返回环境变量中的用户Path?

[英]How to return only user Path in environment variables without access to Registry?

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. 这是我想要实现的:我正在编写一个基于Python的软件,它需要在Windows中的环境变量中将新目录附加到PATH In order to do that, I first get the path, then modify the string, and last use SETX to update the new PATH. 为了做到这一点,我首先获取路径,然后修改字符串,最后使用SETX更新新的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. 我的问题:我尝试了三种获取PATH的方法(使用python或cmd),但它们都返回了USER PATH和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). 我不能接受用户路径和系统路径的组合,因为这会导致新用户PATH太长,并被截断为1024个字符(由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 . 在这种情况下,使用Registry似乎可以解决这个问题: 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". 当我在commend行上运行它时,它返回“Access is denied”。 As a result, I am looking for method that return only user Path in environment variables without access to Registry. 因此,我正在寻找只返回环境变量中的用户Path而无法访问Registry的方法。 Thank you. 谢谢。

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". 虽然我说我想要一个无法访问注册表的答案,但事实证明这是获取用户环境变量“PATH”的唯一方法。 Thank you everyone. 谢谢大家。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM