Pythonでレジストリキーが存在するかどうかを確認してください
-
21-12-2019 - |
質問
Pythonとレジストリキーが存在するかどうかを確認する方法を探しています。
これを行うにはどうすればよいか、レジストリキーが存在するかどうかを確認する必要があるコードを確認する必要がありますか?
解決
前の答えにはいくつかの情報があるように見えますここ
のようなもの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-registry williballenthin このクロスをするために使用できます。プラットフォームで、レジストリを操作するときに多数の素晴らしいオプションがあります。
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
. 所属していません StackOverflow