Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การเข้าถึงรีจิสทรีของ Windows โดยใช้ Python (winreg)


ในฐานะที่เป็นภาษาที่ใช้งานได้หลากหลายและความพร้อมใช้งานของโมดูลที่ผู้ใช้รองรับจำนวนมาก เราพบว่า python นั้นดีในการเขียนโปรแกรมระดับ OS ในบทความนี้เราจะมาดูกันว่า python สามารถเข้าถึง Registry ของระบบปฏิบัติการ Windows ได้อย่างไร

เราจำเป็นต้องนำเข้าโมดูลชื่อ winreg ในสภาพแวดล้อมของหลาม

ในตัวอย่างด้านล่าง เราใช้โมดูล winreg เพื่อเชื่อมต่อกับรีจิสทรีก่อนโดยใช้ฟังก์ชัน ConnectRegistry จากนั้นจึงเข้าถึงรีจิสทรีโดยใช้ฟังก์ชัน OpenKey สุดท้ายเราออกแบบ for loop เพื่อพิมพ์ผลลัพธ์ของคีย์ที่เข้าถึงได้

ตัวอย่าง

import winreg
#connecting to key in registry
access_registry = winreg.ConnectRegistry(None,winreg.HKEY_LOCAL_MACHINE)

access_key = winreg.OpenKey(access_registry,r"SOFTWARE\Microsoft\Windows\CurrentVersion")
#accessing the key to open the registry directories under
for n in range(20):
   try:
      x =winreg.EnumKey(access_key,n)
      print(x)
   except:
      break

ผลลัพธ์

การเรียกใช้โค้ดด้านบนทำให้เราได้ผลลัพธ์ดังต่อไปนี้:

ApplicationFrame
AppModel
Appx
Audio
Authentication
AutoRotation
BITS
Casting
ClosedCaptioning
CloudExperienceHost
Component Based Servicing
……..
…..