44 lines
1.3 KiB
Python
44 lines
1.3 KiB
Python
|
|
import keyboard
|
|||
|
|
import time
|
|||
|
|
import sys
|
|||
|
|
|
|||
|
|
# 可配置参数
|
|||
|
|
START_STOP_KEY = '-' # 启动/停止按键
|
|||
|
|
HOLD_KEY = 'w' # 程序运行时持续按下的键
|
|||
|
|
EXIT_KEY = 'esc' # 注意:虽然你要求ESC不退出,但我们会忽略它
|
|||
|
|
|
|||
|
|
# 状态变量
|
|||
|
|
is_running = False
|
|||
|
|
should_exit = False
|
|||
|
|
|
|||
|
|
def on_p_pressed(e):
|
|||
|
|
global is_running
|
|||
|
|
if e.event_type == keyboard.KEY_DOWN:
|
|||
|
|
is_running = not is_running
|
|||
|
|
if not is_running: # 当停止时立即释放按键
|
|||
|
|
keyboard.release(HOLD_KEY)
|
|||
|
|
print(f"程序 {'已启动' if is_running else '已停止'}")
|
|||
|
|
|
|||
|
|
def main():
|
|||
|
|
print(f"程序已启动,按 {START_STOP_KEY} 键开始/停止,按 Ctrl+C 退出")
|
|||
|
|
print(f"程序运行时将持续按下 {HOLD_KEY} 键")
|
|||
|
|
|
|||
|
|
keyboard.hook_key(START_STOP_KEY, on_p_pressed)
|
|||
|
|
|
|||
|
|
try:
|
|||
|
|
while not should_exit:
|
|||
|
|
if is_running:
|
|||
|
|
keyboard.press(HOLD_KEY)
|
|||
|
|
# 保持按键状态,但允许其他事件处理
|
|||
|
|
time.sleep(0.1)
|
|||
|
|
else:
|
|||
|
|
time.sleep(0.1)
|
|||
|
|
except KeyboardInterrupt:
|
|||
|
|
print("\n程序通过 Ctrl+C 退出")
|
|||
|
|
finally:
|
|||
|
|
if is_running:
|
|||
|
|
keyboard.release(HOLD_KEY)
|
|||
|
|
keyboard.unhook_all()
|
|||
|
|
|
|||
|
|
if __name__ == "__main__":
|
|||
|
|
main()
|