python
复制代码
import winreg
def rename_key(old_key_path, new_key_name):
"""
修改注册表的key名称
:param old_key_path: 旧key路径
:param new_key_name: 新key名称
:return:
"""
# 打开旧key
old_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, old_key_path)
# 获取旧key的信息
key_info = winreg.QueryInfoKey(old_key)
# 获取旧key的所有值和类型
values = {}
for i in range(key_info[1]):
value_name, value_data, value_type = winreg.EnumValue(old_key, i)
values[value_name] = (value_data, value_type)
# 创建新key
new_key_path = old_key_path.rsplit('\\', 1)[0] + '\\' + new_key_name
new_key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, new_key_path)
# 复制旧key的所有键值到新key
try:
for i in range(1024):
name, value, type_ = winreg.EnumValue(old_key, i)
winreg.SetValueEx(new_key, name, 0, type_, value)
except WindowsError as e:
pass
# 将旧key中所有子项复制到新key中
for i in range(key_info[0]):
sub_key_name = winreg.EnumKey(old_key, i)
sub_key_path = old_key_path + '\\' + sub_key_name
sub_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key_path)
sub_key_info = winreg.QueryInfoKey(sub_key)
sub_new_key_path = new_key_path + '\\' + sub_key_name
sub_new_key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, sub_new_key_path)
# 将子项中所有值复制到新子项中
for j in range(sub_key_info[1]):
value_name, value_data, value_type = winreg.EnumValue(sub_key, j)
winreg.SetValueEx(sub_new_key, value_name, 0, value_type, value_data)
# 关闭子项句柄
sub_new_key.Close()
sub_key.Close()
# 关闭旧key句柄
old_key.Close()
# 删除旧key
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, old_key_path)
def test_rename_key():
# 创建一个测试key
test_key_path = r'Software\test_key'
test_key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, test_key_path)
winreg.SetValueEx(test_key, 'test_value', 0, winreg.REG_SZ, 'test_data')
# 测试rename_key函数
rename_key(test_key_path, 'new_test_key')
# 检查新key是否存在
try:
new_test_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\new_test_key')
new_test_value = winreg.QueryValueEx(new_test_key, 'test_value')[0]
assert new_test_value == 'test_data'
print('测试通过')
except Exception as e:
print('测试失败:', e)
# 删除测试key
winreg.DeleteKey(winreg.HKEY_CURRENT_USER, r'Software\new_test_key')
test_rename_key()