python中的异步等待/非阻塞等待

mah*_*uel 2 python nonblocking wait

我喜欢在等待一段时间后输出字符串的每个字母,以获得打字机效果。

for char in string:
     libtcod.console_print(0,3,3,char)
     time.sleep(50)
Run Code Online (Sandbox Code Playgroud)

但这会阻塞主线程,并且程序变为非活动状态。
直到它完成你不能再访问
注:libtcod使用

Ser*_*lis 6

除非有什么阻止您这样做,否则只需将其放入线程中。

import threading
import time

class Typewriter(threading.Thread):
    def __init__(self, your_string):
        threading.Thread.__init__(self)
        self.my_string = your_string

    def run(self):
        for char in self.my_string:
            libtcod.console_print(0,3,3,char)
            time.sleep(50)

# make it type!
typer = Typewriter(your_string)
typer.start()
# wait for it to finish
typer.join()
Run Code Online (Sandbox Code Playgroud)

这将防止睡眠阻塞您的主要功能。

穿线的文档可以在这里找到
一个体面的例子可以在这里找到