How can I get a list of available serial ports using 'serial.tools.list_ports' python module?
Asked Answered
H

2

5

I'm new to python and I need a list of available serial ports to choose one of them in a program. According to This, the serial.tools.list_ports module can do that for me by executing serial.tools.list_ports.comports() method. Accordingly,I executed the following code in python interpreter:

import serial.tools.list_ports
a=serial.tools.list_ports.comports()
print(a)

the result is:

[<serial.tools.list_ports_linux.SysFS object at 0x7f2503d27be0>]

while when I use the following command in ubuntu terminal

python3 -m serial.tools.list_ports

it returns what I want:

/dev/ttyUSB0        
1 ports found

where is the problem?

Humbert answered 2/8, 2019 at 10:21 Comment(2)
What does print(a[0]) output?Ell
Thanks! It worked .We should access to the object attributes like name, device and ... .In pyserial docs it said the output is a ListPortInfo object. but here is SysFs and it has no __bases__ attribute.Humbert
C
9

According to the documentation you've linked,

The function returns a list of ListPortInfo objects.

They have several attributes which you can use, for example device:

Full device name/path, e.g. /dev/ttyUSB0

In order to emulate the command python3 -m serial.tools.list_ports, you could do:

import serial.tools.list_ports

ports = serial.tools.list_ports.comports()
for p in ports:
    print(p.device)
print(len(ports), 'ports found')

Which is a simplified version of what it actually does.

Chubb answered 2/8, 2019 at 11:18 Comment(0)
K
3

An easier way that returns list (using answers above/below) is using .device while iterating through the list of ports obtained from list_ports.comports()

eg.

ports = serial.tools.list_ports.comports()
# 'com_list' contains list of all com ports

com_list = []

for p in ports:
    com_list.append(p.device)
Kolnos answered 21/1, 2021 at 8:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.