[英]Python can you ignore time.sleep outside of function but not inside?
I want to execute a function that waits a certain of time between printing text, but when you call the function it doesnt wait there.我想执行一个在打印文本之间等待一段时间的函数,但是当您调用该函数时,它不会在那里等待。 Here's my code这是我的代码
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)
You should usethreads to allow the program to execute several instructions concurrently:您应该使用线程来允许程序同时执行多条指令:
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()
This will achieve the result.这将达到结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.