-使用keyboard库来监听键盘按键
# 使用keyboard库需要先安装,可以使用pip命令进行安装
pip install keyboard
import keyboard
while True:
# do something
# 检测是否按下了esc键
if keyboard.is_pressed('esc'):
break # 退出循环
# quit() # 退出程序
方法一:
import threading
import keyboard
def do_something():
while True:
print("执行任务")
# 检测是否按下了esc键
if keyboard.is_pressed('esc'):
break # 退出循环
# quit() # 退出程序
# 创建线程并启动
t = threading.Thread(target=do_something)
t.start()
# 等待esc键按下
keyboard.wait('esc')
方法二:
import threading
import keyboard
import time
def do_something():
while True:
print("执行任务")
time.sleep(5)
# 创建线程并启动
t = threading.Thread(target=do_something, daemon=True)
t.start()
# 等待esc键按下
keyboard.wait('esc')