利用python中的shell32()函数实现系统环境变量的读写操作
发布时间:2023-12-29 03:57:16
在Python中,可以使用winreg模块中的OpenKey、QueryValue、SetValue和CloseKey函数来读取和写入系统环境变量。
首先,导入winreg模块:
import winreg
接下来,创建一个函数来读取系统环境变量。在Windows系统中,系统环境变量保存在HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment路径下的Path键中。我们可以使用OpenKey和QueryValue函数来读取该键的值:
def read_environment_variable():
# 打开注册表
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control\Session Manager\Environment')
# 读取Path键的值
value = winreg.QueryValueEx(key, 'Path')
# 关闭注册表
winreg.CloseKey(key)
# 返回Path键的值
return value[0]
接下来,创建一个函数来写入系统环境变量。我们可以使用SetValue函数来设置Path键的值:
def write_environment_variable(value):
# 打开注册表
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control\Session Manager\Environment', 0, winreg.KEY_ALL_ACCESS)
# 设置Path键的值
winreg.SetValueEx(key, 'Path', 0, winreg.REG_SZ, value)
# 刷新环境变量
winreg.SendMessage(winreg.HWND_BROADCAST, winreg.WM_SETTINGCHANGE, 0, 'Environment')
# 关闭注册表
winreg.CloseKey(key)
下面是一个完整的使用示例:
import winreg
def read_environment_variable():
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control\Session Manager\Environment')
value = winreg.QueryValueEx(key, 'Path')
winreg.CloseKey(key)
return value[0]
def write_environment_variable(value):
key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r'System\CurrentControlSet\Control\Session Manager\Environment', 0, winreg.KEY_ALL_ACCESS)
winreg.SetValueEx(key, 'Path', 0, winreg.REG_SZ, value)
winreg.SendMessage(winreg.HWND_BROADCAST, winreg.WM_SETTINGCHANGE, 0, 'Environment')
winreg.CloseKey(key)
# 读取系统环境变量
print(read_environment_variable())
# 写入系统环境变量
write_environment_variable('C:\\Python\\Scripts')
# 读取系统环境变量
print(read_environment_variable())
在 次运行该示例时,它将读取并打印出系统环境变量。然后,它将设置新的系统环境变量,并刷新系统环境变量。最后,它将再次读取并打印出系统环境变量,以验证操作是否成功。
请注意,需要以管理员身份运行Python脚本,以便具有足够的权限来读取和写入系统环境变量。
希望这能帮助到你!
