Search code examples
pythonpython-3.xregistrywinreg

_winreg.QueryValueEx returns "mixed typed" binary value


Under Python 3.4, I'm using winreg.QueryValueEx() to get key values from the registry in order to compare it to text files. I've encountered a problem where the REG_BINARY key value is bytes but in it there are unicode values:

  • Expected Registry key value - 52 50 43 46 01 1b 00 00 00 ff fe ff 04 46 00 6c 00 61...
  • Returned key value - b'RPCF\x01\x1b\x00\x00\x00\xff\xfe\xff \x04F\x00l\x00a\x00t\x00\x00\n\x00\x8b...' (bolded some problematic values)
  • tried some decode\encode options, all failed due to the mixed type (e.g. key_val.decode('utf-8') returned {UnicodeDecodeError}'utf-8' codec can't decode byte 0xff in position 9: invalid start byte)

I use the returned value, which is a list of hex values, to a text file holding expected hex values. These bolded values are not expected since they are not in hex format and I don't know them all in advance to do some workarounds to handle them specifically.

In Python 2.7, there wasn't any problem. I'm guessing this has to do with Python 3 separating str and bytes or even a bug in winreg in Python 3.

Would appreciate any assistance and tip in order to unify it to a single type. Thanks!


Solution

  • Looks like your data in the registry is not even unicode. Do you even need to decode it to unicode?

    Why not store the data in a binary file?

    bytes_data = winreg.QueryValueEx(your_key)
    with open("filename.txt", "wb") as stream:
        stream.write(bytes_data)