async wait / non blocking wait in python

只愿长相守 提交于 2019-12-05 07:28:12

问题


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)

But this blocks the main thread, and the program turns inactive.
You cant access it anymore until it finishes
Note: libtcod is used


回答1:


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.

The documentation for threading can be found here
A decent example can be found here



来源:https://stackoverflow.com/questions/16691576/async-wait-non-blocking-wait-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!