python - 使用 while 循环的装饰器

标签 python python-3.x while-loop jupyter-notebook python-decorators

假设我想重复执行任何函数 5 秒。 我可以做这样的事情:

def any_function(name):
  print(f"hello {name}")
import time
timeout = 5   # [seconds]
timeout_start = time.time()
while time.time() < timeout_start + timeout:
  time.sleep(1) # optional, just to slow down execution
  any_function("id3a") #could be any function

如果我想让这个 while 循环可用于其他函数,我尝试使用装饰器 - 见下文 - 但它会在第一次迭代后破坏 while 循环。

def decorator_function(original_function):
  import time
  timeout = 5   # [seconds]
  timeout_start = time.time()
  while time.time() < timeout_start + timeout:
    def wrapper_function(*args, **kwargs):
      time.sleep(1) # optional, just to slow down execution
      return original_function(*args,**kwargs)
    return wrapper_function
  
@decorator_function
def any_function(name):
  print(f"hello {name}")
  
any_function("id3a")

你会怎么做?

最佳答案

如果您想使用装饰器,这里有一个工作示例:

import time


def scheduler(timeout=5, interval=0):
    def decorator(function):
        def wrapper(*args, **kwargs):
            timeout_start = time.time()
            while time.time() < timeout_start + timeout:
                time.sleep(interval)
                function(*args, **kwargs)
        return wrapper
    return decorator


@scheduler(timeout=5, interval=1)
def any_function(name):
    print(f'hello {name}')


any_function('id3a')

它给出了输出:

hello id3a
hello id3a
hello id3a
hello id3a
hello id3a

如果你想创建另一个函数来重复调用你的函数,这里有一个例子:

import time


def scheduler(function, timeout=5, interval=0):
    timeout_start = time.time()
    while time.time() < timeout_start + timeout:
        time.sleep(interval)
        function()


def any_function(name):
    print(f'hello {name}')


scheduler(lambda: any_function('id3a'), timeout=5, interval=1)

输出为:

hello id3a
hello id3a
hello id3a
hello id3a
hello id3a

关于python - 使用 while 循环的装饰器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63416931/

相关文章:

python - 将 .DAT 文件导入 Pandas 数据框

python - 使用 hmac 生成瑞典 BankID Python 动画 QR 代码

python - 分离 __iter__ 和 __next__ 方法

python-3.x - 使用 yaml 覆盖命名空间

c++ - 为什么该值不断变化多次?

python - django-elasticsearch-dsl : how to search across multiple documents?

python - 如何克隆列表以使其在分配后不会意外更改?

python-3.x - 使用 Sagemaker 生命周期配置文件安装多个包

C 反向函数不适用于 32 个字符

c - 满足基本条件后,程序不会终止递归循环