带有PySerial对象的Python多线程 [英] Python Multi-threading with PySerial object

查看:424
本文介绍了带有PySerial对象的Python多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一般都不熟悉Python和编程.我正在尝试使用pyserial编写设备驱动程序.我打开了一个线程,该线程将从设备读取数据并将其发送到标准输出.在我的主循环中,我使用了一个函数,该函数将从std中读取指令作为字符串,然后使用字典将其写入设备.

I am new to Python and programming in general. I am trying to write a device driver using pyserial. I opened a thread that would read data from the device and send it to std out. On my main loop I used a function that would read instructions from std in as strings and write them to the device using a dictionary.

我的程序正在读取我的指令,但未显示任何应从设备中取出的数据-我知道它正在写入设备,因为当我在字典中未使用指令时,它会崩溃.这是我的代码的结构:

My program is reading my instructions but is not displaying any data that should be coming out of the device - I know its writing to the device because it crashes when I use an instruction not in my dictionary. Here is how my code is structured:

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)

在多线程编程中处理串行对象的正确方法是什么?

What is the proper way to handle serial objects in multi-threaded programming?

推荐答案

您可以这样做:

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)

这篇关于带有PySerial对象的Python多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆