Search code examples
pythonwinreg

How write local time (REG_BINARY) to registry with _winreg Python


How should I deal with value?

def add():
    ts = "Software\\Test\\ti"
    try:
        key = _winreg.CreateKeyEx(_winreg.HKEY_CURRENT_USER, ts, 0, _winreg.KEY_ALL_ACCESS)
    except:
        return False
    else:
        value = hex(int(time.time()))[2::].decode('hex')[::-1].encode('hex')
        """TODO: I should do what?"""
        _winreg.SetValueEx(key, "test", 0, _winreg.REG_BINARY, 3, value)
        _winreg.CloseKey(key)
        return True

the right result in registry like this (I hope): test REG_BINARY 29 96 98 52 00 00 00 00


Solution

  • You should pass binary string; Use struct.pack with <Q (unsigned long long: 8 bytes) as format:

    >>> import struct
    >>> import time
    >>> x = int(time.time())
    >>> x
    1385879197
    >>> hex(x)
    '0x529ad69d'
    >>> struct.pack('<Q', x)
    '\x9d\xd6\x9aR\x00\x00\x00\x00'
    

    Complete code example:

    import struct
    import time
    import _winreg
    
    def add():
        ts = "Software\\Test\\ti"
        try:
            key = _winreg.CreateKeyEx(_winreg.HKEY_CURRENT_USER, ts, 0,
                                      _winreg.KEY_ALL_ACCESS)
        except:
            return Falseimport struct
    import time
    import _winreg
    
    def add():
        ts = "Software\\Test\\ti"
        try:
            key = _winreg.CreateKeyEx(_winreg.HKEY_CURRENT_USER, ts, 0,
                                      _winreg.KEY_ALL_ACCESS)
        except:
            return False
        else:
            value = struct.pack('<Q', int(time.time())) # <-------
            _winreg.SetValueEx(key, "test", 0, _winreg.REG_BINARY, value)
            _winreg.CloseKey(key)
            return True
    
    add()