首页 > 解决方案 > Python 你可以在函数之外忽略 time.sleep 而不是在函数内部吗?

问题描述

我想执行一个在打印文本之间等待一段时间的函数,但是当你调用该函数时它不会在那里等待。这是我的代码

import keyboard, time

def book1():
    print("This is a book")
    time.sleep(2)
    print("These are the contents of the book")

def book2():
    print("This is another book")
    time.sleep(2)
    print("These are the contents of the book")  

books = {
    "a": book1,
    "b": book2
}

def scan_key(key):
    if key.name in books.keys():
        if key.event_type == keyboard.KEY_DOWN:
            book = books[key.name]
            print("Reading book")
            book()
            #This should be printed right after "Reading book" without any wait
            print("Hello")

hook = keyboard.hook(scan_key)

标签: python

解决方案


您应该使用线程来允许程序同时执行多个指令:

import threading

def scan_key(key):
    if key.name in books.keys():
        if key.event_type == keyboard.KEY_DOWN:
            book = threading.Thread(target=books[key.name])
            print("Reading book")
            book.start()
            #This should be printed right after "Reading book" without any wait
            print("Hello")
            book.join()

这将达到结果。


推荐阅读