iokit.IOServiceGetMatchingServices在Python3下断了?

2024-06-28 19:02:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚买了一台运行Yosemite的macmini(我通常使用linux)。我只是想serial.tools.list_端口.comports()在Python3下工作。在

我已经将问题缩小到以下代码片段(从pyserial中提取):

import ctypes
from ctypes import util

iokit = ctypes.cdll.LoadLibrary(ctypes.util.find_library('IOKit'))

kIOMasterPortDefault = ctypes.c_void_p.in_dll(iokit, "kIOMasterPortDefault")

iokit.IOServiceMatching.restype = ctypes.c_void_p

iokit.IOServiceGetMatchingServices.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p]
iokit.IOServiceGetMatchingServices.restype = ctypes.c_void_p

serial_port_iterator = ctypes.c_void_p()

print('kIOMasterPortDefault =', kIOMasterPortDefault)

response = iokit.IOServiceGetMatchingServices(
    kIOMasterPortDefault,
    iokit.IOServiceMatching('IOSerialBSDClient'),
    ctypes.byref(serial_port_iterator)
)
print('serial_port_iterator =', serial_port_iterator)

如果我在python2下运行,那么它可以正常工作:

^{pr2}$

但是,当我在Python3下运行它时,它失败了(串行端口迭代器保持为c_void_p(None))

383 >python3 bug.py
kIOMasterPortDefault = c_void_p(None)
serial_port_iterator = c_void_p(None)

有人知道为什么在Python3下会失败,也许还有如何修复它?在


Tags: 端口importnoneportutilserialctypespython3
1条回答
网友
1楼 · 发布于 2024-06-28 19:02:01

好吧-想清楚了。在

Python3将字符串作为unicode(宽)字符串传递,而Python2将字符串作为窄字符串传递。在

所以改变这条线

iokit.IOServiceMatching('IOSerialBSDClient'),

阅读

^{pr2}$

使它适用于Python2和3。在

现在看看我能不能把零钱换成pyserial。在

相关问题 更多 >