首页 > 解决方案 > the windows API does not work with python3 but works with python 2

问题描述

I have a python script that I'm trying to convert from python 2.7 to python 3.7. The script includes windows API to read the system registry. In python 2.7 it works correctly. In python 3.7 it does not return the correct result.

I try to run the script python 3 in another PC with python 3. I run the script only in powershell like administrator. https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexa this is the documentation of RegOpenKeyExA() function. In python 2.7 I installed "VCForPython27.msi" from: https://download.microsoft.com/download/7/9/6/796EF2E4-801B-4FC4-AB28-B59FBF6D907B/VCForPython27.msi which for windows 3.7 I don't find a updated version.

from ctypes import c_uint, c_char_p, byref, windll
subkey = 'JD'    

def RegOpenKeyEx(subkey):
        hkey = c_uint(0) ## Initialize to an int
        windll.advapi32.RegOpenKeyExA(0x80000002, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\' + subkey, 0, 0xF003F , byref(hkey))
        print(hkey.value)
        return hkey.value

In python 2.7 the output is: 656 and the windll.advapi32.RegOpenKeyExA function returns 0 as a return value.

In python 3.7 the output is: 0 and the windll.advapi32.RegOpenKeyExA function returns 2 as a return value

标签: python-3.xwindows

解决方案


我解决了将第 6 行替换为:

windll.advapi32.RegOpenKeyExA(0x80000002, 'SYSTEM\\CurrentControlSet\\Control\\Lsa\\'.encode('ascii') + subkey.encode('ascii'), 0, 0x19 , byref(hkey))

在 Python 2.7 中,字符串默认为字节字符串。在 Python 3.x 中,它们默认为 unicode。我使用 .encode('ascii') 明确地将字符串设为字节字符串。


推荐阅读