简体   繁体   English

如何使用“serial.tools.list_ports”python 模块获取可用串行端口的列表?

[英]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.我是 python 的新手,我需要一个可用串行端口的列表来在程序中选择其中一个。 According to This , the serial.tools.list_ports module can do that for me by executing serial.tools.list_ports.comports() method.根据Thisserial.tools.list_ports模块可以通过执行serial.tools.list_ports.comports()方法为我做到这一点。 Accordingly,I executed the following code in python interpreter:因此,我在 python 解释器中执行了以下代码:

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而当我在ubuntu终端中使用以下命令时

python3 -m serial.tools.list_ports

it returns what I want:它返回我想要的:

/dev/ttyUSB0        
1 ports found

where is the problem?问题出在哪儿?

According to the documentation you've linked,根据您链接的文档,

The function returns a list of ListPortInfo objects.该函数返回ListPortInfo对象的列表。

They have several attributes which you can use, for example device :它们有几个您可以使用的属性,例如device

Full device name/path, eg /dev/ttyUSB0完整的设备名称/路径,例如/dev/ttyUSB0

In order to emulate the command python3 -m serial.tools.list_ports , you could do:为了模拟命令python3 -m serial.tools.list_ports ,您可以执行以下操作:

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 .这是它实际作用的简化版本。

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()返回列表(使用上面/下面的答案)的一种更简单的方法是使用 .device 同时遍历从 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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM