如何使用_winreg Python将本地时间(REG_BINARY)写入注册表

时间:2013-12-01 06:17:27

标签: python winreg

我应该如何处理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

这样的注册表中的正确结果(我希望): test REG_BINARY 29 96 98 52 00 00 00 00

1 个答案:

答案 0 :(得分:2)

你应该传递二进制字符串;将struct.pack<Q(无符号长long:8字节)一起使用格式为:

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

完整的代码示例:

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()