레지스트리 키가 파이썬이 있는지 확인합니다
-
21-12-2019 - |
문제
레지스트리 키가 파이썬이 있는지 확인하는 방법을 찾고 있습니다.
레지스트리 키가 존재하는지 여부를 확인해야합니까?
을 확인해야합니다.해결책
이전 답변에서 몇 가지 정보가있는 것처럼 보입니다 여기 .
프로그램이 읽을 수 있기를 원하기 때문에 존재를 확인하고 있습니까?핵심을 확인하기 위해 Key 키를 누르면 try-except
블록으로 랩핑 할 수 있습니다.이렇게하면 "경쟁 조건"을 방지 할 수 있으므로 (밝히지 않게) 그 존재를 확인하고 실제로 키를 읽는 동안 수정 된 경우 수정됩니다.같은 것 :
from _winreg import *
key_to_read = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall'
try:
reg = ConnectRegistry(None, HKEY_LOCAL_MACHINE)
k = OpenKey(reg, key_to_read)
# do things with the key here ...
except:
# do things to handle the exception here
. 다른 팁
이것은 오래된 게시물이지만 비슷한 검색 후에 나는 이것에 몇 가지 정보를 추가 할 것으로 생각했습니다. winreg
, 내가 발견 한 것부터 Windows 환경에서만 작동합니다. python-breg / williballenthin 을 사용 하여이 크로스 - 플랫폼을 사용하면 레지스트리 작업을 할 때 다양한 훌륭한 옵션이 있습니다.
값을 꺼낼 값이있는 대상 키가있는 경우 다음 단계에 따라 나열 할 수 있습니다 .... 첫째, 모듈 가져 오기 (PIP 설치 Python-Registry). 이것은 마스터 폴더가 libs / sitePackages에 삽입되면 레지스트리 폴더가 사이트 패키지의 루트에 있는지 확인할 수 없을 수 있습니다.
from Registry import Registry # Ensure Registry is in your libs/site-packages
.
다음으로 기능을 작성하고 try:
및 except
Into에 추가 할 수 있는지 확인하십시오.
# Store internal Registry paths as variable, may make it easier, remove repeating yourself
time_zone = "ControlSet001\\Control\\TimeZoneInformation"
# STORE the path to your files if you plan on repeating this process.
<Path_To_reg_hive> = "C:\\Users\\Desktop\\Whatever_Folder\\SYSTEM"
def get_data():
registry = Registry.Registry(<Path_To_reg_hive>) # Explicitly, or use variable above
try:
key = registry.open(time_zone) # Registry.Registry opens reg file, goes to the path (time_zone)
except Registry.RegistryKeyNotFoundException: # This error occurs if Path is not present
print("Sorry Bud, no key values found at : " + time_zone) # If not there, print a response
.
이 프로세스를 통해 확인하려는 모든 것을 확인하려는 모든 것을 한 번에 확인하거나 한 번에 하나씩 확인할 수 있습니다. 다음은 작업 예제입니다.
from Registry import Registry
# These can be included directly into the function, or separated if you have several
system = "SYSTEM" # or a Path, I have a SYSTEM hive file in my working environment folder
time_zone = "ControlSet001\\Control\\TimeZoneInformation123" # Path you want to check, added 123 so its not there
def get_data():
registry = Registry.Registry(system) # Explicitly, or use variable above
try:
key = registry.open(time_zone) # Registry.Registry opens reg file, goes to the path (time_zone)
except Registry.RegistryKeyNotFoundException: # This error occurs if Path is not present
print("Sorry Bud, no key values found at : " + time_zone) # If not there, print a response
# key is identified above only to use later, such as.... for v in key.subkeys(): Do more stuff
get_data()
.
를 반환하는
.Sorry Bud, no key values found at : ControlSet001\Control\TimeZoneInformation123