# pyserial 如何同时读写串口数据？

> 原文链接：https://robotics.hellobike.com/pitfalls/2019-11-27-robotics-se-11897
> 频道：pitfalls | 更新日期：2019-11-27 | 标签：auto, stackexchange, arduino, serial
> 核心摘要：pyserial 不应关闭再重开串口，可用多线程，或单线程写后用可用字节检查/短超时读取。

# pyserial 如何同时读写串口数据？

::: v-pre
> 本文由 AI 根据公开内容整理，可能有误，请以原文为准：[how to read and write data with pyserial at same time](https://robotics.stackexchange.com/questions/11897/how-to-read-and-write-data-with-pyserial-at-same-time)（Robotics Stack Exchange #11897）

**状态**：已解决

## 问题

提问者只能用 pyserial 单独写或读，想在同一程序中同时读写 Arduino 串口；示例中写入后关闭串口、再打开并 `readline()`。

## 环境

嵌入式控制器 / 串口通信

## 解决办法

1. 不要在写入后关闭再重新打开串口。
2. 若设备可随时写入且可随时接收数据，使用多线程分别处理读和写。
3. 若不用多线程，在单线程循环中先检查是否有数据要写，有则写入；再检查读端是否有可用字节，或给读取设置短超时，避免读取长期阻塞。
4. 循环中如无事可做可短暂 sleep，避免 CPU 占用 100%；同时确保硬件读缓冲足够容纳待读取的数据。

原问题作者：user14148；采纳答案作者：kaliatech。原内容依 CC BY-SA 4.0 授权，本页摘要同样依 CC BY-SA 4.0 授权。
:::

## 原始参考来源 (Sources)

- [Robotics Stack Exchange #11897：how to read and write data with pyserial at same time](https://robotics.stackexchange.com/questions/11897/how-to-read-and-write-data-with-pyserial-at-same-time)