3

我正在尝试制作一个 Python 串行端口侦听器应用程序。

我的问题是在后台运行侦听器功能而不杀死 GUI。

这是代码:

import sys
import getopt
import serial
from time import sleep
from threading import *
from Tkinter import *
import io
#ser = serial.serial_for_url('loop://', timeout=1)
#sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))

runing = True
ser = None
class App:
  global ser
  def __init__(self, master):
    varCOM = StringVar(master)
    varCOM.set("COM1")
    listbox = OptionMenu(master, varCOM, "COM1", "COM2", "COM3", "COM4")
    listbox.grid(row=0, column=0)

    varBaudRate = StringVar(master)
    varBaudRate.set(4800)
    listboxBaudrate = OptionMenu(master, varBaudRate, 300, 1200, 2400, 4800, 9600, 14400, 19200, 38400)
    listboxBaudrate.grid(row=0, column=1) 

    varParity = StringVar(master)
    varParity.set("None")
    listboxParity = OptionMenu(master, varParity, "None", "Even", "ODD", "Mark", "Space")
    listboxParity.grid(row=1, column=0)

    varDataBits = StringVar(master)
    varDataBits.set(8)
    listboxDataBits = OptionMenu(master, varDataBits, 5, 6, 7, 8)
    listboxDataBits.grid(row=1, column=1)

    varStopBits = StringVar(master)
    varStopBits.set(2)
    listboxStopBits = OptionMenu(master, varStopBits, 1, 2)
    listboxStopBits.grid(row=2, column=0)

  def detener():
    global runing
    runing = False
    detencion = Thread(target=detener)

  def detencionRun():
    detencion.run()

  def write():
    while runing == True:
      #sleep(10)
      line = ser.read(14)
      if line:
        print line
        file.write(line)
    itinerancia = Thread(target=write)

  def openPort(port='COM1', baudrate=1920, bytesize=8, parity='N', stopbits=1):
    try:
      global ser
      global file
      port = varCOM.get()
      baudrate = int(varBaudRate.get())
      bytesize = int(varDataBits.get())
      stopbits = int(varStopBits.get()) 
      ser = serial.Serial(port=port, baudrate=baudrate, bytesize=bytesize, parity=parity, stopbits=stopbits)
      file = open("lecture.txt", "a")
      file.write("-- INICIO PROGRAMA --\n")

      itinerancia.run()
      #while runing == True:
      #  line = ser.read(14)
      #  if line:
      #    print line
      #    file.write(line)
      file.write("\n-- FIN DEL PROGRAMA --\n")
      file.close()
    except serial.SerialException:
        print 'No se pudo abrir el puerto'
    return

  def ejecutar():
    detener = Button(master, text="Detener", command=detencionRun)
    detener.grid(row=3, column=0)

    t = Thread(target=openPort)
    t.run()

    ejecutar = Button(master, text="Ejecutar", command=ejecutar)
    ejecutar.grid(row=3, column=1)


if __name__ == '__main__':
  root = Tk()
  app = App(root)
  root.mainloop()

应用程序在 while 循环中冻结。 应用程序冻结 抱歉我的英语和编码不好(我是 Python 新手)

4

1 回答 1

0

您可以尝试对您的应用程序进行多线程处理并将轮询和文件写入放在其他线程中,或者您可以尝试将端口读取和文件写入分配到较大程序循环中的较小块中,以便处理大块数据不会完全阻止程序的执行。请记住,如果您确实尝试将其打包,您可能需要使用读写缓冲区进行设置,这样您就不会在完全写入或处理之前意外转储或覆盖内存中的数据它。

于 2012-04-30T18:26:48.053 回答