python - 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)
解决方案
您应该使用线程来允许程序同时执行多个指令:
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()
这将达到结果。
推荐阅读
- python - 如何用 Python 解决这个继承问题?
- android - 在领域中按日期排序
- symfony - 覆盖 Knp 菜单模板
- amazon-web-services - 旧的 AWS Lambda 层会自动删除吗?如果没有,如何删除它们?
- docker - 在 Docker compose 中将 Ceph OSD 连接到集群时出错
- python - 在散点图上标记异常值
- javascript - 如何模糊 HTML5 视频标签的特定区域?
- javascript - katex 方程到图像(png,jpg)
- javascript - 如何从迁移中生成 Sequelize 模型?
- c++ - 是“僵局”吗?如何在多线程中避免它?