python-3.x - 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
解决方案
我解决了将第 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') 明确地将字符串设为字节字符串。
推荐阅读
- c++ - CodeBlocks 错误“numeric_limits”未在此范围内声明
- python - 如何通过jinja2排除。我的意思是与包含相反
- javascript - 在“窗口”上捕获之前的事件气泡
- javascript - 如何在此代码中使用多个频道 ID
- node.js - 如何将 NodeJS 表单数据对象转换为 JSON 字符串
- c# - C#从具有特定类属性重复值的类列表中删除元素
- ldap - 如何使用 curl 命令获取某个 LDAP 组的用户列表?
- tensorflow - GAN - 模型的损失和评估
- react-native - 致命异常:java.lang.IndexOutOfBoundsException setSpan (2 ... 2) 超出长度 0 -React Native
- javascript - 如何将谷歌字体添加到 React Native?