2015-06-13 37 views
1

我剛剛收到了一個運行Yosemite的mac mini(我通常使用linux)。我試圖讓serial.tools.list_ports.comports()在Python3下工作。iokit.IOServiceGetMatchingServices在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,那麼它工作正常:

382 >python bug.py 
('kIOMasterPortDefault =', c_void_p(None)) 
('serial_port_iterator =', c_void_p(4355)) 

然而,當我在Python3下運行它時,它失敗(serial_port_iterator保留爲c_void_p(None))

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

有人知道爲什麼這會在Python3下失敗,並且可能如何解決它?

回答

1

好的 - 算出來了。

Python3將字符串作爲unicode(寬)字符串傳遞,而Python2將字符串作爲窄字符串傳遞。

所以更改此行

iokit.IOServiceMatching('IOSerialBSDClient'), 

閱讀

iokit.IOServiceMatching(b'IOSerialBSDClient'), 

使其成爲Python2工作,3

我們看到,如果我能得到改變成pyserial。