python中的异步等待/非阻塞等待 [英] async wait / non blocking wait in python
本文介绍了python中的异步等待/非阻塞等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我喜欢等待一段时间后输出字符串的每个字母,以获得打字机效果.
i like to output each letter of a string after waiting some time, to get a typewriter effect.
for char in string:
libtcod.console_print(0,3,3,char)
time.sleep(50)
但这会阻塞主线程,程序变得不活跃.
在它完成之前你不能再访问它
注意:libtcod 使用
But this blocks the main thread, and the program turns inactive.
You cant access it anymore until it finishes
Note: libtcod is used
推荐答案
除非有什么阻止你这样做,把它放到一个线程中.
Unless there is something preventing you from doing so, just put it into a thread.
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()
这将防止睡眠阻塞您的主要功能.
This will prevent the sleep blocking your main function.
这篇关于python中的异步等待/非阻塞等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文