繁体   English   中英

如何在 while 循环中使用变化的变量值 | Python

[英]How to use a changing variable value in a while loop | Python

我有一个 python 程序和一个用烧瓶编写的服务器。 我想做的是向服务器发送一个请求,询问是否有任何新订单。 如果存在active: True值应该运行我的脚本。 当脚本运行时,我的程序应该继续发送请求,因为当程序运行时, active值可以更改为False 如果active: False脚本应该停止,但我必须继续向服务器发送请求以检查新订单。

我在下面添加一个例子。 如果您有任何疑问,请告诉我:

import time

def read_active_data():
    pass

def my_func(active):
    while True:
        print("my_func is active")
        if active == False:
            break


count=0
active=False

while True:
    if count%10==0:
        active= read_active_data()
    if active==True:
        my_func(active)
    time.sleep(1)
    count+=1

我这样解决了:

from threading import Thread
import time

count=0
active= False

def set_active():
    global active
    global count
    while True:
        if count%10==0:
            if active:
                active=False
                print("Inactive")
            else:
                active=True
                print("Active")
        time.sleep(1)

def kronos():
    global count
    while True:
        time.sleep(1)
        count+=1
        print("Count is: ",count)

def execute():
    global active
    while True:
        if active:
            print("Executing")
        else :
            print("Not executing")
        time.sleep(1)

if __name__ == '__main__':
    t1 = Thread(target=set_active)
    t2 = Thread(target=kronos)
    t3 = Thread(target=execute)
    t1.start()
    t2.start()
    t3.start()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM