Python在Windows上获取系统环境变量 [英] Python get system environment variables on windows

查看:593
本文介绍了Python在Windows上获取系统环境变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Windows上获取系统环境变量?使用以下代码,我仅获取用户环境变量:

How can I get system environment variables on windows? With the below codes I only get the user environment variables:

os.environ['PATH']

否则返回的结果相同:

os.getenv('PATH')

谢谢!

推荐答案

基于(已删除的)注释,我找到了解决方案.如果python脚本是由用户而不是管理员运行的,则应从注册表中读取系统环境变量.

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]

这篇关于Python在Windows上获取系统环境变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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