【发布时间】:2020-06-23 10:03:54
【问题描述】:
我有一个将串行数据写入文本文件的程序。我想首先通过读取文件来检查文本文件中的特定卡 UID,如果已经有卡 UID 我想跳过串行写入步骤(串行写入 0),如果没有那个卡 UID 我会继续并串行写入 1。
为了检查卡 UID,我使用了下一个命令,请查看我的代码。
import threading
import serial
import sys
import io
import codecs
import queue
from pynput import keyboard
with io.open("uid.txt", "w", encoding="utf-8") as b:
b.write("")
q = queue.Queue()
ser = serial.Serial('COM4', baudrate = 9600, timeout = 5)
class SerialReaderThread(threading.Thread):
def run(self):
while True:
output = ser.readline().decode('utf-8')
print(output)
q.put(output)
class FileWriting(threading.Thread):
def run(self):
while True:
output = q.get()
with io.open("uid.txt", "r+", encoding="utf-8") as input:
for line in input:
if line.startswith("Card UID: "):
s = (next(input))
if line.startswith(s): ***
ser.write(b'0\r\n')
else:
ser.write(b'1\r\n')
with io.open("uid.txt", "a+", encoding="utf-8") as f:
f.write(output)
serial_thread = SerialReaderThread()
file_thread=FileWriting()
serial_thread.start()
file_thread.start()
serial_thread.join()
file_thread.join()
FileWriting 线程是我需要帮助的。同样,我想首先读取文本文件(最初创建时为空)并检查带有卡 UID 的行,并查看文件中是否已经存在该特定卡 UID,如果没有则写入 0串行写1。
但是运行这段代码给我一个错误:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\Tsotne\AppData\Local\Programs\Python\Python38-32\project\fff.py", line 36, in run
s = (next(input))
StopIteration
【问题讨论】:
-
您的意思是要检查
output是否是UID保存在uid.txt文件中?并将它们全部收集到uid.txt文件中? -
如果让您感到困惑,我很抱歉,我会尽力解释得更好。串口信息保存在
uid.txt文件中,串口上有很多卡被扫描每张卡都有它唯一的卡UID,我基本上想检查卡是否已经被扫描,所以代码不会允许将 1 串行写入同一张卡两次。如果文本文件中已经有特定的卡 UID,我基本上需要检查文本文件。 -
那么你为什么需要一个文件?你能把这些信息保存在内存中吗?
-
我只是认为这是最简单的方法。但我会接受你可能有的任何建议。
标签: python file pyserial file-writing