在从数据库读取时不间断地运行python循环

问题描述 投票:0回答:1

我正在制作一个带有覆盆子pi 3的7段显示器(4个显示器)记分板。我做了一个python程序,从数据库中读取2个数字并将它们存储在一个变量中,检查有多少位数(因为我只能发送一个数字到一个显示器)然后它将正确的信息发送到GPIO引脚。每个数字开启0.001s,因此0.004s全部通过4.然后循环总共200次重复,然后返回并检查数据库中是否有任何更改。

但是,当它从数据库重新读取时,所有显示都会关闭。我想知道是否有可能继续使用先前存储的变量循环(具有200次重复的循环)并且仅在数据库完成读取新信息之后用新的循环重新启动它。

#i have set up the database and all other important stuff outside this loop
while 1:
    digitTipe = 0   
    digitTipe2 = 0
    timer = 0  #counter for the GPIO loop

    #it gets the info from db and then it lists the digits
    cur.execute("SELECT gol_domaci FROM tekme ORDER BY id DESC LIMIT 0, 1") 
    db.commit()
    home_team = cur.fetchall()
    for q in home_team-:
        digits= list(int(d) for d in str(q[0]))



    #same but for the other team
    cur.execute("SELECT gol_gosti FROM tekme ORDER BY id DESC LIMIT 0, 1")
    db.commit()
    guest_team = cur.fetchall()
    for e in guest_team:
        digit2 = list(int(d) for d in str(e[0]))



    #here checks if both digits are the same (11, 22, 33...), is just one digit(3, 6, ...) or if is just a random number (12, 23, 45,...)
    #based on these results the GPIO output knows how to properly send out voltage... i tried with other methods but this one works for me
    if len(digit) < 2:
        digitTipe = 1
    else:
        if digit[0] == digit[1]:
            digitTipe = 2
    if len(digit2) < 2:
        digitTipe2 = 1
    else:
        if digit2[0] == digit2[1]:
            digitTipe2 == 2



    while timer < 200:  #this is the loop that has code for GPIO pins
    #("insert digit output code")

“滞后”并不坏,最多只有0.1秒,但这是显而易见的,令人讨厌,所以我的“同事”希望它固定下来。但如果可能的话,我不想制作两个单独的代码文件

我很抱歉编码的质量很差。这是我在python中的第一个“真正的”程序。我也很抱歉,如果我不够具体,因为它也恰好是我在stackoverflow上的第一个问题。提前致谢!

python mysql raspberry-pi lag
1个回答
2
投票

从我收集的,while timer < 200: …循环激活显示。因此,当由于cur.execute(…)等而未执行此循环时,显示器将被停用。

解决方案是使用异步编程。这是一个关于这个主题的好问题:asynchronous programming in python

这是一个复制并粘贴其中一个答案的例子(作者Jesse Dhillon):

from threading import Thread

def background_stuff():
  while True:
    print "I am doing some stuff"

t = Thread(target=background_stuff)
t.start()

# Continue doing some other stuff now

您可以创建两个类似于background_stuff的函数,一个用于处理显示,另一个用于从数据库中获取信息。然后基于这两个函数实例化两个线程,并启动它们。所以:

# declare variables here
def handle_display():
    while True:
        # put here what is under the `while timer < 200: … ` loop

def fetch_from_db():
    # every time timer runs out, fetch info from database
    # and store in variables declared at line 1

t1 = Thread(target=handle_display)
t2 = Thread(target=fetch_from_db)
t1.start()
t2.start()

© www.soinside.com 2019 - 2024. All rights reserved.