gpt4 book ai didi

python - 在 Python 上运行后台循环

转载 作者:行者123 更新时间:2023-11-28 19:26:30 25 4
gpt4 key购买 nike

我正在尝试制作一个 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 循环中卡住。 The app freezed抱歉我的英语和编码不好(我是 Python 新手)

最佳答案

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

关于python - 在 Python 上运行后台循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10388102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com