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

Okay, using the windows registry became easier with the newest versions of Python but do you exctly know where the keys have to be placed? You just want to store some data for your progam in the windows registry without fiddling around with SetValue() etc. Have a look at this class:

Python, 52 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import _winreg as wreg
import cPickle as pickle

class WindowsRegistry:

    def __init__(self, company="spirito GmbH", project="TestProg", write=1):
        """
        handle registry access
        """
        self.write = write
        self.company = company
        self.project = project
        self.keyname = "Software\\%s\\%s" % (self.company, self.project)

        try:
            self.key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, self.keyname)
        except:
            if self.write:
                self.key = wreg.CreateKey(wreg.HKEY_CURRENT_USER, self.keyname)

    def set(self, name, value):
        " set value in registry "
        if not self.write:
            raise Exception, "registry is read only"
        wreg.SetValue(self.key, name, wreg.REG_SZ,str(value))

    def pset(self, name, value):
        " set using pickle "
        self.set(name, pickle.dumps(value))

    def get(self, name):
        " get value out of registry "
        return wreg.QueryValue(self.key, name)

    def pget(self, name):
        " get using pickle "
        return pickle.loads(self.get(name))

    def close(self):
        " close the key finally "
        self.key.Close()

    def __del__(self):
        self.close()


if __name__=="__main__":
    r = WindowsRegistry(project="MyTestProg", write=1)
    r.set("test", "hello string data")
    r.pset("testp", 123)
    print r.get("test")
    print r.pget("testp")

Modify and to your values and then put data in the regsitry via set() for string data and pset() for Python objects. You can read them via get() and pget(). That's all. Data will be stored in the place of the Windows Registry where it belongs to.

Add a comment

Sign in to comment