So I've got a serial device, however the serial port changes most times I reconnect it. What I want to do is to list all serial ports, iterate over them until I find the correct one, and then connect to that one. I know that I can list all ports from the commandline like:
$ python -m serial.tools.list_ports
/dev/cu.YYYY
/dev/cu.XXXX
ZZZZ ports found
I want to do that from a python, but this doesn't work:
>>> import serial
>>> for port in serial.tools.list_ports:
... print(f'Current port: {port}')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'serial' has no attribute 'tools'
What can I do? I really don't want to execute python -m serial.tools.list_ports
as an external shell command, as it just seems silly since the library already has an API for python scripts.
Thanks!
I don't know if I can explain it, but sometimes Python is fussy about dotted imports. Also to get an iterable within a script, you can use comports()
Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial.tools.list_ports
>>> for port in serial.tools.list_ports.comports():
... print(f'Current port: {port}')
...
Current port: COM1 - Communications Port (COM1)
>>>
The serial.tools.list_ports module is documented here.