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

时间:2018-11-03 16:03:35

标签: 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)

1 个答案:

答案 0 :(得分:0)

功能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()