使用PySerial对象的Python多线程
一般来说,我对Python和编程都是新手。我正在尝试使用pyserial编写设备驱动程序。我打开了一个线程,该线程将从设备读取数据并将其发送到std out。在我的主循环中,我使用了一个函数,该函数将std中的指令作为字符串读取,并使用字典将它们写入设备 我的程序正在读取我的指令,但没有显示任何应该从设备中输出的数据-我知道它正在写入设备,因为当我使用字典中没有的指令时,它会崩溃。下面是我的代码的结构:使用PySerial对象的Python多线程,python,multithreading,pyserial,Python,Multithreading,Pyserial,一般来说,我对Python和编程都是新手。我正在尝试使用pyserial编写设备驱动程序。我打开了一个线程,该线程将从设备读取数据并将其发送到std out。在我的主循环中,我使用了一个函数,该函数将std中的指令作为字符串读取,并使用字典将它们写入设备 我的程序正在读取我的指令,但没有显示任何应该从设备中输出的数据-我知道它正在写入设备,因为当我使用字典中没有的指令时,它会崩溃。下面是我的代码的结构: import serial import threading #ser is my seri
import serial
import threading
#ser is my serial object
def writeInstruction(ser):
#reads an instruction string from stdin and writes the corresponding instruction to the device
instruction = raw_input('cmd> ')
if instr == 'disable_all': defaultMode(ser)
else: ser.write(dictionaryOfInstructions[instruction])
time.sleep(.5)
def readData(ser):
# - Reads one package from the device, calculates the checksum and outputs through stdout
# - the package content (excludes the Package head, length, and checksum) as a string
while True:
packetHead = binascii.hexlify(ser.read(2))
packetLength = binascii.hexlify(ser.read(1))
packetContent = binascii.hexlify(ser.read(int(packetLength, 16) - 1))
if checkSum(packetHead + packetLength + packetContent):
print packetContent
readThread = threading.Thread (target = readData, args = ser)
readThread.start()
while True:
writeInstr(ser)
在多线程编程中,处理串行对象的正确方法是什么?您可以这样做:
import serial
from threading import Thread
from functools import wraps
# decorate the function - start another thread
def run_async(func):
@wraps(func)
def async_func(*args, **kwargs):
func_hl = Thread(target = func, args = args, kwargs = kwargs)
func_hl.start()
return func_hl
return async_func
@run_async #use asyncronously
def writeInstruction(ser):
#reads command from stdin
#Writes the command to the device (enabling data output)
@run_async #use asynchronously
def readData(ser):
#reads the packets coming from the device
#prints it through std out
your_arg = 'test'
writeInstruction(your_arg)
了解您在
readData(ser)
中尝试执行的操作会有所帮助。我想知道你的线程是否在你得到任何数据之前就完成了。还有writeInstruction(ser)
您能从这些功能中提供更多的代码吗?writeInstruction(ser)打开设备的数据采集(医疗设备)readData(ser)从设备读取单个数据包并对其进行校验。发布的代码不足以诊断问题。如果可能,请尝试发布。在writeInstruction()
中的变量pm
是什么?如果不是ser
?是的,它是ser,editedI获取线程。错误:无法启动新线程回溯:writeInstr(ser),func_h1.start()只需对声明的任何函数使用@run_async,并且需要异步,它就会工作。不知道您是否希望它在循环中运行