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

การเข้าถึง Windows Registry ด้วย Python (winreg)

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

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

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

ตัวอย่าง

import winreg
# เชื่อมต่อกับคีย์ใน Registry
access_registry = winreg.ConnectRegistry(None, winreg.HKEY_LOCAL_MACHINE)
access_key = winreg.OpenKey(access_registry, r"SOFTWARE\Microsoft\Windows\CurrentVersion")
# เข้าถึงคีย์เพื่อเปิดไดเรกทอรี Registry ภายใต้
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 ……… ……..