如何只返回用户环境变量中的Path,而不能访问注册表? [英] How to return only user Path in environment variables without access to Registry?

查看:247
本文介绍了如何只返回用户环境变量中的Path,而不能访问注册表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要实现的:
我正在编写一个基于Python的软件,这将需要在Windows中的环境变量中添加新的目录到 PATH 。为了做到这一点,我首先得到路径,然后修改字符串,最后使用SETX来更新新的PATH。

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.

我的问题:
I尝试三种方法获取PATH(使用python或cmd),但它们都返回了USER PATH和SYSTEM 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')

我不能接受用户路径和系统路径,因为这将导致新的用户PATH太长,被截断为1024个字符(由Microsoft限制)。我已经阅读了一个完全相同的问题的帖子。在这种情况下,使用注册表似乎可以解决问题: http ://stackoverflow.com/questions/13359082/windows-batch-select-only-user-variables 。该解决方案建议使用

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.

推荐答案

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')

虽然我说我想要一个没有访问注册表的答案,结果是这是获取用户环境变量PATH的唯一方法。谢谢大家。

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.

这篇关于如何只返回用户环境变量中的Path,而不能访问注册表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆