首页 > 解决方案 > Python:在带有按钮的函数中添加开/关功能

问题描述

我编写了一个小型多线程程序,它以元素方式将列表附加到熊猫数据帧,此附加函数在单独的线程上运行,并每两秒将列表中的一个元素附加到数据帧,第二个函数称为 check_signal( ) 在主线程的 while 循环中运行,并使用生成器根据数据帧元素的值输出特定信号。可以在脚本中配置此生成器的阈值。

我想在程序中添加用户可以启动和停止 check_signal() 函数并更改/修改阈值的功能,我计划从 GUI 像 plotly Dash 那样做,我已经写了按钮等,但我不能把我的头脑围绕在逻辑上,任何人都请帮忙:

工作代码,请复制粘贴以在您的系统上运行:

import pandas as pd 
import numpy as np
import time 
import threading 


##############################
##############################
# This is to simulate data coming from a websocket , external stream etc.
##############################
##############################

# Define threading lock 
lock = threading.Lock()


# Define list of random numbers , can be very long 
a = [2,3,4,5,6,0,8,7,1,3,4,0,6,4,0,2,4,0,4,5,0,1,7,0,1,8,5,3,6,3,4,5,6,7,8,3,2,0.5,-1,-2,3,4,5,6,7,8,9,7,8,8,6,5,3,4,5]

# Define Empty DataFrame 
df = pd.DataFrame(columns=['pct_diff'])


# Create the function to append to 
def append_to_frame():
    global df
    for i in a :
        df = df.append(pd.DataFrame({'pct_diff' : [i]}))
        #print(df['pct_diff'][-1])
        time.sleep(2)
# Run function on thread 
t_1 = threading.Thread(target=append_to_frame, args=(), daemon=True)

#---------------------------------------------------------------------------------------------


##############################
##############################
# This part we define our generator and check signal function,
# this is wehere I want to add the switch on/off functionality 
##############################
##############################

# Define generator which will generate signal based on upper threshold ut and 
# lower threshold lt
def signal(ut, lt):
    current_state = "Outside market"

    while True:
        pct_change = yield current_state

        if (
            current_state in ("Outside market", "Market exit")
            and pct_change >= ut
        ):
            current_state = "Entered market"
        elif current_state == "Entered market" and pct_change > lt:
            current_state = "Inside market"
        elif current_state == "Market exit" and pct_change < ut:
            current_state = "Outside market"
        elif (
            current_state in ("Entered market", "Inside market")
            and pct_change < lt
        ):
            current_state = "Market exit"

# Instantiate generator with parameters
s = signal(5,2) # Configure upper and lower threshold 
next(s)

# Define check signal function 
def check_signal():
    while True:
        signal = s.send(df['pct_diff'].iloc[-1])
        print("Percent Diff : {}, Sgnal : {}".format(df['pct_diff'].iloc[-1], signal))
        time.sleep(3)


# Start append function on thread 
with lock:
    t_1.start()

# Start check signal in while loop 
check_signal()

标签: pythonpython-3.xpandaspython-multithreadingplotly-dash

解决方案


推荐阅读