跳转到主要内容

Python中处理超时的简单方法

项目描述

EggTimer

有些通用模式既优雅又简单,而有些则不是。

常见解决方案

from time import time, sleep

max_sleep_time_sec = 1.5

start_time = time()
timeout_sec = 42.0

while time() - start_time < timeout_sec:
    # Do or check some stuff

    time_remaining = timeout_sec - (time() - start_time)
    if time_remaining > max_slep_time_sec:
        sleep(min(time_remaining, max_sleep_time_sec))
    else:
        sleep(max_sleep_time_sec)

这个循环的目的是什么?哦,我明白了,它是一个超时。我的循环条件中的操作顺序正确吗?我是否正确计算了time_remaining?我的if子句正确吗?提示:它不正确。如果我在设置start_time之后系统时钟被更新,这段代码的行为是否正常?提示:它不正常。这段代码在我的应用程序中重复了多少次?

我们可以做得更好。 EggTimer可以帮助。

EggTimer 示例

from time import sleep

from eggtimer import EggTimer

max_sleep_time_sec = 1.5

timer = EggTimer()
timer.set(42.0)

while not timer.is_expired():
    # Do or check some stuff

    sleep(min(timer.time_remaining_sec, max_sleep_time_sec))

啊,这样更好!清晰、简洁、可重用且易于表达。缺陷的风险也显著降低!

安装

使用pip install -U egg-timer进行安装

文档

EggTimer - 用于检查是否已经过去了一定时间的类。

ThreadSafeEggTimer - EggTimer的线程安全实现。

请参阅EggTimer 示例了解如何使用EggTimeThreadSafeEggTimer具有相同的接口。

类文档

Python 3.10.4 (main, Jun 29 2022, 12:14:53) [GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from eggtimer import EggTimer
>>> help(EggTimer)
Help on class EggTimer in module eggtimer.eggtimer:

class EggTimer(builtins.object)
 |  A class for checking whether or not a certain amount of time has elapsed.
 |
 |  Methods defined here:
 |
 |  __init__(self)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  is_expired(self)
 |      Check whether or not the timer has expired
 |
 |      :return: True if the elapsed time since set(TIMEOUT_SEC) was called is greater than
 |               TIMEOUT_SEC, False otherwise
 |
 |  reset(self)
 |      Reset the timer without changing the timeout
 |
 |  set(self, timeout_sec: float)
 |      Set a timer
 |
 |      :param timeout_sec: A non-negative floating point number expressing the number of
 |                          seconds to set the timeout for.
 |
 |  ----------------------------------------------------------------------
 |  Readonly properties defined here:
 |
 |  time_remaining_sec
 |      Return the amount of time remaining until the timer expires.
 |
 |      :return: The number of seconds until the timer expires. If the timer is expired, this
 |               function returns 0 (it will never return a negative number).
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)

>>>

运行测试

运行测试与执行 poetry install && poetry run pytest 一样简单。

许可证

EggTimer 是开源软件,遵循 GNU 通用公共许可证 v3.0。

项目详情


下载文件

下载适合您平台文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源代码发行版

egg_timer-1.3.0.tar.gz (16.1 kB 查看哈希值)

上传时间 源代码

构建发行版

egg_timer-1.3.0-py3-none-any.whl (19.5 kB 查看哈希值)

上传时间 Python 3

由以下提供支持