mstfyghm
mstfyghm

Reputation: 53

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

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?

Upvotes: 5

Views: 26718

Answers (2)

AanisNoor
AanisNoor

Reputation: 53

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)

Upvotes: 3

mkrieger1
mkrieger1

Reputation: 23152

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.

Upvotes: 9

Related Questions