首页 > 解决方案 > 需要检查事件是否已经发生然后退出(无限)循环,但程序必须连续运行

问题描述

我正在尝试用 Python 编写一个小程序来搜索网页表格中的某些特定值。最终我可以通过一个名为Alert_Red. 我需要每 5 秒自动调用一次该函数,但是当我尝试下面的代码时,它给了我正确的值,但在一个无限循环中。

[...some code above...]

def Alert_Red():
    if advColor == avc_red and delta <= fivesec_datetime:
        print('New RED advisory please check the following link: ', link)
        if advColor1 == avc_red and adv_datetime1 == adv_datetime:
            print('Another new RED advisory please check the following link: ', link)

schedule.every(5).seconds.do(Alert_Red)

while True:
    schedule.run_pending()
    time.sleep(1)

输出第一个“if 子句”为真:

New RED advisory please check the following link: , link
New RED advisory please check the following link: , link
New RED advisory please check the following link: , link
[endless loop every 5 sec]

输出第二个“if 子句”为真:

Another new RED advisory please check the following link: , link
Another new RED advisory please check the following link: , link
Another new RED advisory please check the following link: , link
[endless loop every 5 sec]

程序必须连续运行(即使 if 子句为真,因为我需要始终检查它们)但我只需要被告知一次(第一次找到值和/或如果它们发生变化)和我需要的输出是:

New RED advisory please check the following link: ', link

或者对于第二个“if子句”为真:

Another new RED advisory please check the following link: ', link

标签: pythonfunctionloopsif-statementschedule

解决方案


如果我了解您的问题,可以使用一个跟踪您是否发布咨询的全局变量来解决它。在此函数之外(在您的启动代码中的某处)将此变量初始化为 False。

def Alert_Red():
    global advised
    if advColor == avc_red and delta <= fivesec_datetime:
        if not advised:
            print('New RED advisory please check the following link:', link)
            advised = True
        if advColor1 == avc_red and adv_datetime1 == adv_datetime:
            if not advised:
                print('Another new RED advisory please check the following link: ', link)               
                advised = True
 

推荐阅读