python - 如何停止/恢复循环而不必终止终端?
问题描述
这是一个游戏的小宏。
我想用 F9 键停止程序(不要关闭它!),然后当我再次单击 F9 时,它将恢复。如果可能,无需退出游戏。
F9 - 启动/停止程序
import pyautogui
import time
import keyboard
print("Press F10 to stop and F9 to start")
while keyboard.is_pressed('f10') == False:
if keyboard.is_pressed('f9') == True:
time.sleep(3)
pyautogui.press('w')
time.sleep(1)
pyautogui.press('s')
time.sleep(1)
pyautogui.press('w')
time.sleep(1)
pyautogui.press('s')
time.sleep(1)
pyautogui.press('a')
time.sleep(4)
pyautogui.press('t')
解决方案
你可以使用pynput来监控键盘
from time import sleep
from threading import Thread
from pynput.keyboard import Key, Listener, Controller
def on_press(key):
if key == Key.f9: # start and stop the macro
flags['running'] = not flags['running']
elif key == Key.f10: # closes the program
flags['exit'] = True
return False # stop the listener
def macro(flags):
keyboard = Controller()
while not flags['exit']:
if flags['running']: # your macro here
sleep(3)
keyboard.type('w')
# etc...
flags = {'running' : True, 'exit' : False}
macro_thread = Thread(target=macro, args=(flags,))
macro_thread.start()
# Collect events until released
with Listener(on_press=on_press) as listener:
listener.join()
macro_thread.join()
如果您希望代码立即停止,您需要更改宏函数内的睡眠:
from time import time
def check_exit(s, flags):
""" checks if the exit flag becomes true for s seconds """
start = time()
while time() < (start + s):
if flags['exit']:
return True
return False
def macro(flags):
keyboard = Controller()
while not flags['exit']:
if flags['running']:
if check_exit(3, flags): return
keyboard.type('w')
# etc...