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

时间:2013-05-22 12:19:25

标签: python wait nonblocking

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

for char in string:
     libtcod.console_print(0,3,3,char)
     time.sleep(50)

但这阻止了主线程,程序变为非活动状态。
你不能再访问它,直到它完成为止 注意:libtcod用于

1 个答案:

答案 0 :(得分:4)

除非有阻止你这样做的事情,否则只需将其放入一个帖子中即可。

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()

这样可以防止睡眠阻碍您的主要功能。

线程文档可以是found here
一个不错的例子可以是found here