如何在每次打印前创建延迟?

How to create a delay before each print?

你好,我正在用 Python 创建一个基于文本的游戏,我想在每个打印语句之前有一秒钟的延迟。

我目前的解决方案是:

time.sleep(1)
name = input('Do you happen to remember what your name was? ').capitalize()
print(name + ", that's a nice name.")
time.sleep(1)
print("Well it seems that you are all better now so I'm going to have to let you go")

但是,每次打印前都要放一个time.sleep很烦人!

所以我想知道是否有人知道更有效的方法。

为什么不用函数来做呢?

def dprint(s, delay=1):
    time.sleep(delay)
    print(s)

你还好吗?

dprint("hello")

如果您需要此功能是临时的但对于所有 print() 函数子调用,您可以像这样使用 mock.patch() 修补 print() 函数:

import time
from unittest import mock

OLD_PRINT = print

def make_delayed_print(delay):

    def delayed_print(*args, **kwargs):
        time.sleep(delay)
        OLD_PRINT(*args, **kwargs)

    return delayed_print


with mock.patch('builtins.print', make_delayed_print(1)):
    print(1)
    print(2)

这是我的做法,它将支持对 print() 的所有现有调用,而无需将被调用函数的名称更改为其他名称,并且它支持多个参数和关键字参数(就像常规 print() 函数执行):

import time

DELAY = 1
regular_print = print  # Save built-in function.

def print(*args, **kwarg):
    time.sleep(DELAY)
    regular_print(*args, **kwarg)