Welcome, guest | Sign In | My Account | Store | Cart

The code below shows how to read from/write to the Windows Registry. In this example all the tasks are listed which are executed at logon. A new task (opening the explorer) is added to ths logon.

Python, 24 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from _winreg import *

print r"*** Reading from SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***"
aReg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)

aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") 
for i in range(1024):                                           
    try:
        n,v,t = EnumValue(aKey,i)
        print i, n, v, t
    except EnvironmentError:                                               
        print "You have",i," tasks starting at logon..."
        break          
CloseKey(aKey)                                                  

print r"*** Writing to SOFTWARE\Microsoft\Windows\CurrentVersion\Run ***"
aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", 0, KEY_WRITE)
try:   
   SetValueEx(aKey,"MyNewKey",0, REG_SZ, r"c:\winnt\explorer.exe") 
except EnvironmentError:                                          
    print "Encountered problems writing into the Registry..."
CloseKey(aKey)

CloseKey(aReg)            

For more information on the Windows Registry see - Python Library Reference: 20.2 _winreg - Windows registry access - http://whatis.techtarget.com/definition/0,289893,sid9_gci212883,00.html

2 comments

Marcos Sánchez Provencio 22 years, 8 months ago  # | flag

Backslashes. I think that all of the strings in this example that contain backslashes should be raw strings (such as r"This is an example of a \ backslash")

Zhu 9 years, 7 months ago  # | flag

instead of using random range value, call _winreg.QueryInfoKey(key) to retrieve the exact number of values or subkeys.

aKey = OpenKey(aReg, r"SOFTWARE\Microsoft\Windows\CurrentVersion\Run") 
for i in range(QueryInfoKey(aKey)[1]):
....

https://docs.python.org/2/library/_winreg.html#_winreg.QueryInfoKey

Created by Daniel Kinnaer on Mon, 9 Jul 2001 (PSF)
Python recipes (4591)
Daniel Kinnaer's recipes (1)

Required Modules

Other Information and Tasks