首页 > 解决方案 > 如何制作类似于 print() 但之后等待的函数?

问题描述

我想在 python 中为基于文本的游戏创建一个函数,它打印出给定的参数并在之后等待。

def say(string):
    time.sleep(1.5)
    return string

标签: pythonfunction

解决方案


您可以使用定期轮询,我们可以设置一个条件,所以在满足条件之前它可以等待。

import time

def wait_until(somepredicate, timeout, period=0.25, *args, **kwargs):
  mustend = time.time() + timeout
  while time.time() < mustend:
    if somepredicate(*args, **kwargs): return True
    time.sleep(period)
return False

方法2:

我们可以使用事件对象等待,下面是解释相同的链接。

https://docs.python.org/3/library/threading.html#event-objects


推荐阅读