简体   繁体   中英

async wait / non blocking wait in 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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM