Python winreg говорит, что открыл ключ, которого нет в моем реестреPython

Программы на Python
Anonymous
Python winreg говорит, что открыл ключ, которого нет в моем реестре

Сообщение Anonymous »

Я пытаюсь работать с реестром Windows, и каждый тестируемый мной ключ или значение показывает, что они там, хотя их нет (согласно тестированию regedit и powershell для значений)
Я проверил, мой код открывает 64-битный реестр, Python 64-битный, система 64-битная. Я попытался снова открыть проводник Windows, закрыть и снова открыть реестр и перезапустить систему. Ничего не изменилось.
Для настроек, в которых я создал значение и установил для него атрибут «данные», он сохраняется между сеансами, и я могу проверить его в своем коде, как если бы он его хранил. ГДЕ-ТО.
Это код:

Код: Выделить всё

import winreg

def hive_name(hive):
if hive == winreg.HKEY_CURRENT_USER:
return "HKEY_CURRENT_USER"
elif hive == winreg.HKEY_LOCAL_MACHINE:
return "HKEY_LOCAL_MACHINE"
elif hive == winreg.HKEY_CLASSES_ROOT:
return "HKEY_CLASSES_ROOT"
elif hive == winreg.HKEY_USERS:
return "HKEY_USERS"
elif hive == winreg.HKEY_PERFORMANCE_DATA:
return "HKEY_PERFORMANCE_DATA"
elif hive == winreg.HKEY_CURRENT_CONFIG:
return "HKEY_CURRENT_CONFIG"
else:
return "UNKNOWN_HIVE"

def open_or_create_key(hive, path):
try:
# Open the registry key for reading and writing in 64-bit view
key = winreg.OpenKey(hive, path, 0, winreg.KEY_READ | winreg.KEY_WRITE | winreg.KEY_WOW64_64KEY)
print(f"Key opened: {hive_name(hive)}\\{path}")
except FileNotFoundError:
# Handle if the key doesn't exist
print(f"Creating key: {hive_name(hive)}\\{path}")
key = winreg.CreateKeyEx(hive, path, 0, winreg.KEY_READ | winreg.KEY_WRITE | winreg.KEY_WOW64_64KEY)
except PermissionError:
# Handle if there are permission issues
print(f"Permission denied while accessing the key: {hive_name(hive)}\\{path}")
key = None
except Exception as e:
# Handle any other exceptions
print(f"An error occurred: {e}")
key = None
return key

def get_value(key,which):
try:
value, _ = winreg.QueryValueEx(key, which)
print(f"Current value: {value}")
except FileNotFoundError:
print("Current value: ")
except Exception as e:
print(f"An error occurred while querying the value: {e}")

def set_value(key,which,what):
try:
winreg.SetValueEx(key, which, 0, winreg.REG_DWORD, what)
print (which, "was set to", what)
except FileNotFoundError:
print (which, "could not be set to", what)

def close_key(key):
if key:
winreg.CloseKey(key)
print("Key closed.")

# Test the open_or_create_key function
if __name__ == "__main__":

print("# This key does exist on my system and has tons of values")
print("# Expected Output: Key opened: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced")
key = open_or_create_key(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced")
print("# Value name DisallowShaking is NOT in my registry.")
print("# Expected Output: Current value:   ")
get_value(key,"DisallowShaking")
print("# Value name HideFileExt IS in my registry.")
print("# Expected Output: HideFileExt set to X (where X is the value set in the code) - needs to be checked in the registry to see if it changed between runs")
set_value(key,"HideFileExt",1)
close_key(key)

print("# Neither {86ca1aa0-34aa-4e8b-a509-50c905bae2a2} nor InprocServer32 exist in my registry.")
print("# Expected Output: Creating Key: Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32")
key = open_or_create_key(winreg.HKEY_CURRENT_USER, r"Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32")
close_key(key)

print("# The Blocked key does not exist in my registry.")
print("# Expected Output: Creating Key: SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked")
key = open_or_create_key(winreg.HKEY_CURRENT_USER, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked")
print("# If the key were created, then I can test for value {e2bf9676-5f8f-435c-97eb-11607a5bedf7} which should not exist yet.")
print("# Expected Output: An error occurred while querying the value:  ")
get_value(key,"{e2bf9676-5f8f-435c-97eb-11607a5bedf7}")
close_key(key)

Когда я запускаю вышеуказанное (в терминале VsCode с VsCode, запущенным от имени администратора), я получаю следующий вывод:

Код: Выделить всё

# This key does exist on my system and has tons of values
# Expected Output: Key opened: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
Key opened: HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced
# Value name DisallowShaking is NOT in my registry.
# Expected Output: Current value: 
Current value: 1
# Value name HideFileExt IS in my registry.
# Expected Output: HideFileExt set to X (where X is the value set in the code) - needs to be checked in the registry to see if it changed between runs
HideFileExt was set to 1
Key closed.
# Neither {86ca1aa0-34aa-4e8b-a509-50c905bae2a2} nor InprocServer32 exist in my registry.
# Expected Output: Creating Key: Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32
Key opened: HKEY_CURRENT_USER\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2}\InprocServer32
Key closed.
# The Blocked key does not exist in my registry.
# Expected Output: Creating Key: SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked
Key opened: HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked
# If the key were created, then I can test for value {e2bf9676-5f8f-435c-97eb-11607a5bedf7} which should not exist yet.
# Expected Output: An error occurred while querying the value:
Current value: 
Key closed.
Несмотря на это, состояние моего реестра после выполнения вышеописанного выглядит следующим образом:
  • DisallowShaking был НЕ создано
  • HideFileExt НЕ было установлено в 1
    [img]https:/ /i.sstatic.net/Qhhk8DnZ.png[/img]
  • key Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509 -50c905bae2a2}\InprocServer32 НЕ создан
    Изображение
  • ключ SOFTWARE\Microsoft\Windows\CurrentVersion\Shell Extensions\Blocked НЕ создан
  • значение {e2bf9676-5f8f-435c-97eb-11607a5bedf7 явно не существует, но выводится так, как если бы оно существовало.
    Изображение
И как-то , состояние сохраняется. Я добавил «set_value» к последнему значению ({e2bf9676-5f8f-435c-97eb-11607a5bedf7}) при последующем запуске, и установленное мной значение сохранялось между запусками программы. И ключа, и значения по-прежнему нет в моем реестре.

Подробнее здесь: https://stackoverflow.com/questions/786 ... y-registry

Вернуться в «Python»