在Mac OS X和Python 3中列出串行端口

时间:2014-03-17 23:44:21

标签: macos python-3.x pyserial

我在列出可用的串口时遇到问题,我真的需要帮助调试这个。 在Python 2.7.5中,正确列出了COM端口,而PySerial在Python 3.3.5中返回一个空列表。

我发现另外一个孤独的灵魂在互联网上遇到同样的问题(没有答案),但这个问题似乎并不受欢迎 - 也许这是我的系统?

我正在使用Mac OS X 10.9.2并通过自制软件安装了python和python3。我刚才更新了一切。 PySerial在pip和pip3都是2.7版本。

输出:

Python 2.7.5 (default, Nov  4 2013, 18:04:45) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from serial.tools import list_ports
>>> list_ports.comports()
[['/dev/cu.Bluetooth-Incoming-Port', 'n/a', 'n/a'], ['/dev/cu.Bluetooth-Modem', 'n/a', 'n/a']]

Python 3.3.5 (default, Mar 10 2014, 13:25:50) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from serial.tools import list_ports
>>> list_ports.comports()
[]

2 个答案:

答案 0 :(得分:5)

目前我正在采用以下方法。 PySerial工具坏了。

>>> import glob
>>> glob.glob('/dev/tty.*')
['/dev/tty.Bluetooth-Incoming-Port', '/dev/tty.Bluetooth-Modem']

答案 1 :(得分:2)

问题的根本原因在于python3将字符串编码为unicode(宽)字符串,而python2将字符串编码为窄字符串。

因此,当从iokit调用API函数时,pyserial代码需要传递窄字符串。

我发现其他人也碰到了这个并发布了补丁。您可以在本期末找到他的补丁: http://sourceforge.net/p/pyserial/patches/38/

使用该补丁,我现在从python3获得与python2相同的行为。

我使用macports安装了python3,并在此目录中找到了pyserial for python3的安装: /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/serial

所以我执行了以下操作:

cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/serial/tools
sudo cp list_ports_osx.py list_ports_osx_orig.py
sudo curl -O http://sourceforge.net/p/pyserial/patches/_discuss/thread/603bd426/55a8/attachment/list_ports_osx.py

这使得list_ports.comports()对我有用。