使用PySerial库调用
serial.tools.list_ports.list_ports()
,遍历返回的串口对象列表,提取设备名称、描述API 查找串口的详细实现
串口(Serial Port)是计算机与外部设备通信的重要接口,通过编程接口(API)查找系统中可用的串口,可以实现自动化设备检测、动态端口分配等功能,不同操作系统提供的API和实现方式有所不同。
Windows 系统下查找串口
使用 SetupDiGetClassDevs
函数
Windows 通过 SetupAPI 提供串口设备枚举功能。
关键步骤:
- 初始化
GUID
为串口设备类。 - 调用
SetupDiGetClassDevs
获取设备信息集合。 - 遍历设备信息列表,提取串口名称(如
COM1
)。
代码示例(C++):
#include <windows.h> #include <setupapi.h> #include <stdio.h> void ListSerialPorts() { GUID classGuid = GUID_DEVCLASS_PORTS; // 串口设备类 GUID HDEVINFO hDevInfo = SetupDiGetClassDevs(&classGuid, NULL, NULL, DIGCF_PRESENT); if (hDevInfo == INVALID_HANDLE_VALUE) { printf("Failed to get device list. "); return; } SP_DEVINFO_DATA devInfoData; devInfoData.cbSize = sizeof(SP_DEVINFO_DATA); int index = 0; while (SetupDiEnumDeviceInfo(hDevInfo, index, &devInfoData)) { index++; // 获取设备描述大小 DWORD regDataSize; SetupDiGetDeviceRegistryProperty(hDevInfo, &devInfoData, SPDRP_FRIENDLYNAME, ®DataSize, NULL, 0); char* buffer = new char[regDataSize]; SetupDiGetDeviceRegistryProperty(hDevInfo, &devInfoData, SPDRP_FRIENDLYNAME, ®DataSize, buffer, regDataSize); printf("Found Port: %s ", buffer); delete[] buffer; } SetupDiDestroyDeviceInfoList(hDevInfo); }
输出示例:
Found Port: COM1
Found Port: COM2
Linux 系统下查找串口
读取 /dev/serial/by-path
目录
Linux 系统将串口设备以符号链接形式存放在 /dev/serial/by-path
目录下。
关键步骤:
- 打开
/dev/serial/by-path
目录。 - 读取所有符号链接,解析目标文件名(如
/dev/ttyS0
)。 - 去重后输出串口列表。
代码示例(Python):
import os def list_serial_ports(): serial_path = "/dev/serial/by-path" if not os.path.exists(serial_path): print("No serial ports found.") return [] ports = set() for file in os.listdir(serial_path): target = os.readlink(os.path.join(serial_path, file)) ports.add(os.path.basename(target)) return sorted(ports) if __name__ == "__main__": ports = list_serial_ports() for port in ports: print(f"Found Port: {port}")
输出示例:
Found Port: ttyS0
Found Port: ttyUSB0
跨平台实现对比
特性 | Windows | Linux |
---|---|---|
API 核心函数 | SetupDiGetClassDevs | os.listdir + os.readlink |
设备信息来源 | 注册表(Registry) | /dev/serial/by-path 目录 |
权限要求 | 普通用户可访问 | 需要 root 权限或拨号组(dialout) |
输出格式 | 设备描述(如 COM1 ) | 设备文件名(如 ttyS0 ) |
相关问题与解答
问题 1:如何判断某个串口是否被其他程序占用?
解答:
- Windows:尝试用
CreateFile
打开串口,若返回ERROR_ACCESS_DENIED
或ERROR_SHARING_VIOLATION
,则表示被占用。 - Linux:尝试用
open()
打开设备文件,若返回EBUSY
或EACCES
,则表示被占用。
示例:# Linux 检查 ttyS0 是否被占用 try: fd = open("/dev/ttyS0", "r+b") fd.close() print("Port is free.") except OSError as e: print(f"Port is busy or unavailable: {e}")
问题 2:如何通过 API 获取串口的硬件信息(如厂商、型号)?
解答:
- Windows:使用
SetupDiGetDeviceRegistryProperty
获取SPDRP_MFG
(厂商)和SPDRP_DEVICEDESC
(设备描述)。 - Linux:读取
/sys/class/tty/ttyS0/device/manufacturer
和/sys/class/tty/ttyS0/device/product
文件。
示例:# Linux 获取 ttyS0 的厂商和型号 with open("/sys/class/tty/ttyS0/device/manufacturer") as f: manufacturer = f.read().strip() with open("/sys/class/tty/ttyS0/device/product") as f: product = f.read().strip() print(f"Manufacturer: {manufacturer}, Product: {product}")
涵盖了不同操作系统下通过 API 查找串口的实现
到此,以上就是小编对于“api 查找串口”的问题就介绍到这了,希望介绍的几点解答对大家有用,有任何问题和不懂的,欢迎各位朋友在评论区讨论,给我留言。
【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!
发表回复