python - 需要检查事件是否已经发生然后退出(无限)循环,但程序必须连续运行
问题描述
我正在尝试用 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
解决方案
如果我了解您的问题,可以使用一个跟踪您是否发布咨询的全局变量来解决它。在此函数之外(在您的启动代码中的某处)将此变量初始化为 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
推荐阅读
- r - 遍历数据框并根据条件更改值 [R]
- django - 允许经过身份验证和未经身份验证的用户使用令牌身份验证装饰器访问 django 休息视图
- django - 根据与该模型相关的另一个模型的属性搜索模型的记录?
- c# - 使用 ASP.NET Core 3.0 是否需要为 IActionContextAccessor 进行任何额外的配置?
- css - 从边框向外创建 CSS 脉冲效果
- google-sheets - “查询已完成,输出为空”如何在没有结果时将其置零
- typescript - Cloud Function 在 android 应用程序上返回 null
- xodus - Xodus 实体商店可以共享交易吗?
- ios - 即使在后台并且如果应用程序在 Swift 中被终止,计时器也会继续执行
- python - 如何在python的数据框中查找具有相同值的列列表