source: trunk/src/allmydata/windows/registry.py

Last change on this file was d25140b8, checked in by Itamar Turner-Trauring <itamar@…>, at 2021-05-07T13:36:01Z

Fix flakes on Python 3.

  • Property mode set to 100644
File size: 2.2 KB
Line 
1import sys
2import winreg
3
4_AMD_KEY = r"Software\Allmydata"
5_BDIR_KEY = 'Base Dir Path'
6
7if sys.platform not in ('win32'):
8    class WindowsError(Exception): # stupid voodoo to appease pyflakes
9        pass
10    raise ImportError("registry cannot be used on non-windows systems")
11
12def get_registry_setting(key, name, _topkey=None):
13    """
14    This function iterates through _topkey (if not None),
15    HKEY_CURRENT_USER, and HKEY_LOCAL_MACHINE before giving up.
16
17    @note: Only supports string values.
18
19    @param key: The key we are searching.
20    @type key: String
21
22    @param name: The name of the setting we are querying.
23    @type name: String
24    """
25    topkeys = [winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE]
26
27    if _topkey:
28        topkeys.insert(0, _topkey)
29
30    for topkey in topkeys:
31        try:
32            regkey = winreg.OpenKey(topkey, key)
33
34            sublen, vallen, timestamp = winreg.QueryInfoKey(regkey)
35            for validx in range(vallen):
36                keyname, value, keytype = winreg.EnumValue(regkey, validx)
37                if keyname == name and keytype == winreg.REG_SZ:
38                    return value
39
40        except WindowsError:
41            continue
42    # We didn't find the key:
43    raise KeyError(key, name, "registry setting not found")
44
45def set_registry_setting(key, name, data, reg_type=winreg.REG_SZ,
46                         _topkey=winreg.HKEY_LOCAL_MACHINE, create_key_if_missing=True):
47    """
48    Sets a registry setting.
49
50    defaults to string values (REG_SZ) - overridable with reg_type.
51    """
52    try:
53        regkey = winreg.OpenKey(_topkey, key, 0, winreg.KEY_SET_VALUE)
54    except WindowsError:
55        if create_key_if_missing:
56            regkey = winreg.CreateKey(_topkey, key)
57        else:
58            raise KeyError(key, "registry key not found")
59
60    try:
61        winreg.DeleteValue(regkey, name)
62    except:
63        pass
64
65    winreg.SetValueEx(regkey, name, 0, reg_type, data)
66
67def get_registry_value(keyname):
68    """
69    retrieves a registry key value from within the Software/Allmydata Inc key
70    """
71    try:
72        return get_registry_setting(_AMD_KEY, keyname)
73    except KeyError:
74        return None
75
76def get_base_dir_path():
77    return get_registry_value(_BDIR_KEY)
Note: See TracBrowser for help on using the repository browser.