Python,独立运行程序的一部分

2024-07-05 12:35:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想制作一个python代码,它将:

  1. 从api读取数据并每10分钟刷新一次。

  2. 在LCD显示屏上以每5秒连续变化的两张纸显示此数据

我不知道如何使代码的一部分独立于另一部分运行。 就我而言。。 -BLOCK1每300秒运行一次 -BLOCK2直达

这是我的Python代码。。。当然,它没有工作,还没有完成。 谢谢你的帮助!你知道吗

from urllib import urlopen
import I2C_LCD_driver1
import json
import time
mylcd = I2C_LCD_driver1.lcd()

while True:
    # BLOCK 1 - start every 600s
    CNV7 = urlopen('https://www.coincalculators.io/api/allcoins.aspx?hashrate=12200&power=1400&powercost=0.15&difficultytime=0&algorithm=CryptoNightV7').read()
    dataCNV7= json.loads(CNV7)  
    coinCNV7 = dataCNV7[0]["name"] 
    algoCNV7 = dataCNV7[0]["algorithm"] 
    dayUSDCNV7 = dataCNV7[0]["profitInDayUSD"]
    print ("Algoritm:"),algoCNV7
    print ("Coin:"),coinCNV7
    dayUSDCNV7 = float(dayUSDCNV7)
    dayEUCNV7 = dayUSDCNV7*0.88
    print("%.2f" % dayEUCNV7),("Eu/dan")
    time.sleep(600) # Read API every 10minuts

    # BLOCK 2 - must run non-stop
    if dayEUCNV7 > 3:
        while True:
            print("RELEY ON")
            mylcd.lcd_clear()
            mylcd.lcd_display_string("RELEY - ON",1,0)
            mylcd.lcd_display_string("Profit:",2,0)
            mylcd.lcd_display_string(str(dayEUCNV7),3,2)
            print ("LCD page 1")
            time.sleep(2)

            mylcd.lcd_clear()
            mylcd.lcd_display_string("RELEY- ON",1,0)
            mylcd.lcd_display_string(str(coinCNV7),3,2)
            print ("LCD page 2")
            time.sleep(2)

    else:
        while True:
            print("RELEY OFF")
            mylcd.lcd_clear()
            mylcd.lcd_display_string("RELEY - OFF",1,0)
            mylcd.lcd_display_string("Profit:",2,0)
            mylcd.lcd_display_string(str(dayEUCNV7),3,2)
            print ("LCD page 1")
            time.sleep(2)

            mylcd.lcd_clear()
            mylcd.lcd_display_string("RELEY- OFF",1,0)
            mylcd.lcd_display_string(str(coinCNV7),3,2)
            print ("LCD page 2")
            time.sleep(2)

Tags: importstringlcdtimedisplaysleepprintclear
1条回答
网友
1楼 · 发布于 2024-07-05 12:35:33

执行块1的函数1将每10秒运行一次,考虑到一些执行时间,函数2将连续执行。你知道吗

import threading
import time
def func1(f_stop):
    print(1)
    # BLOCK 1 ...
    if not f_stop.is_set():
        # call func1() again in 10 seconds
        threading.Timer(10, func1, [f_stop]).start()

def func2():
    print(2)
    # BLOCK 2 ...
    time.sleep(2) # For demonstration, remove this line
    threading.Timer(0, func2).start()

# start calling func1 now and every 10 sec thereafter
f_stop = threading.Event()
func1(f_stop)
# Call func2 which will run forever with a delay of 2 sec
func2()

相关问题 更多 >