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

时间:2019-02-25 17:18:07

标签: python mysql raspberry-pi lag

我正在用树莓派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.1s,但是它很引人注目并且令人讨厌,所以我的“同事”希望将其修复。 但是如果可能的话,我不想制作两个单独的代码文件

对不起,编码质量不好。这是我第一个使用python编写的“真实”程序。如果我不够具体,我也很抱歉,因为这恰好是我关于stackoverflow的第一个问题。 预先感谢!

1 个答案:

答案 0 :(得分: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()