python - 串行端口 - 无法读取数据,我只是写了
问题描述
我正在尝试通过串口对两个设备之间的通信进行简单的模拟(在 linux 上要清楚)。我想出了从串口读取数据到不同线程的想法,但问题是这个线程给我一个这样的错误:
Is open? True
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "client.py", line 18, in func
if len(ser.readline()) > 0:
File "/home/bartosz/PycharmProjects/socket-serial-comm/venv/lib/python3.7/site-packages/serial/serialposix.py", line 478, in read
raise portNotOpenError
serial.serialutil.SerialException: Attempting to use a port that is not open
所以似乎我试图使用的端口没有打开,但是当我从这个线程打印时 print("Is open? ", ser.is_open)
它给了我 True,因此我无法在线程中打开端口。
这是我的代码:
import serial
import threading
import time
ser = serial.Serial('/dev/pts/0', timeout=1)
def func():
print("Is open? ", ser.is_open)
while True:
if len(ser.readline()) > 0:
print(ser.readline())
x = threading.Thread(target=func, args=ser)
x.start()
time.sleep(1)
ser.write(b'some text\n')
time.sleep(1)
ser.close()
有什么想法为什么会这样?
解决方案
这与您编写的代码完全相同。
正在读取串行端口的进程永远在无限循环中运行While True:
,但端口本身ser.close()
在处理线程启动后大约 2 秒。
由于ser.readline()
即使在之后执行ser.close()
,也会出现问题错误。
在调用之前ser.close()
,您需要安装一个机制来终止def func():
线程处理。
顺便说一句,用len(ser.readline())
inif
语句判断print(ser.readline())
有数据的过程需要输入两行,但是第一行不显示,只打印下一行会很奇怪。
您应该审查该过程。
推荐阅读
- java - Hashmap 并发问题
- html - 将 2 个饼图并排放置
- c - 使用 malloc 在函数中返回一个 int 数组
- python - 输入形状为 [?,1,2,36], [5,5,36,48] 的“conv2d_7/Conv2D”(操作:“Conv2D”)从 1 中减去 5 导致的负尺寸大小
- reactjs - React 中需要 Antd 单选按钮
- jsf - 从外部事件更改字体大小下拉值选择
- c# - 如何使用 SQL 表中的数据填充 html 页面
- javascript - 如何从 github 中具有 HTTP 的 api 获取数据
- delphi - IOmniPipeline - 第二阶段未执行
- java - 在 Java 方法结束时获取“Process 'command 'C:/Program Files/Java/jdk-13.0.2/bin/java.exe'' 以非零退出值 1 结束”