首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >需要检查事件是否已经发生,然后退出(无限)循环,但程序必须连续运行

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

Stack Overflow用户
提问于 2021-11-09 23:30:26
回答 1查看 29关注 0票数 0

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

代码语言:javascript
复制
[...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子句“为true的输出:

代码语言:javascript
复制
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子句“为true的输出:

代码语言:javascript
复制
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子句为真,因为我需要始终检查它们),但我只需要通知我一次(第一次找到值和/或如果值发生更改时),我需要的输出是:

代码语言:javascript
复制
New RED advisory please check the following link: ', link

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

代码语言:javascript
复制
Another new RED advisory please check the following link: ', link
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-09 23:51:27

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

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69906315

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档