如何获得停止Python代码的用户输入



所以我正在进行一个python编程,可以自动无限期地移动鼠标。我需要一种方法,让用户能够给出一定的输入,以停止鼠标在命令上。我需要补充什么才能做到这一点。下方的代码

from tracemalloc import stop
from unittest import result
import pyautogui
import time 
import random
while True in range (0,5):
x = random.randint(0,5)
y = random.randint(0,5)
pyautogui.moveTo(x,y)
localtime = time.localtime()
result = time.strftime("%I:%M:$S %p", localtime)
print ('Moveed at ' + str(result) + ' (' + str(x) + ',' + str(y) + ')')
time.sleep(2)

如果你想要一个跨平台的解决方案,下面的方法会起作用,但它比只适用于Windows的解决方案更详细。

https://pynput.readthedocs.io/en/latest/keyboard.html#monitoring-键盘

pip install pynput

from pynput import keyboard
from pynput.keyboard import Key
KEY_TO_STOP_PROGRAM = Key.f1
run = True
def on_press(key):
global run
if key == KEY_TO_STOP_PROGRAM:
run = False
# This print statement can be added to see what keys map to what
# in the pynput module
print(key)
if __name__ == "__main__":
listener = keyboard.Listener(
on_press=on_press,
)
listener.start()
while run:
# Your code here
print("I am running")
print("program exit")

如果你只是在Windows上实现键盘模块应该可以工作,但它需要Linux用户的sudo权限,我认为正因为如此,跨平台的解决方案更好。

https://pypi.org/project/keyboard/

pip install keyboard

import keyboard
# Use whatever key you may want
KEY_TO_STOP_PROGRAM = "ctrl + alt"
if __name__ == "__main__":
while True:
# Your code here
#Check if user inputs key to stop program
if keyboard.is_pressed(KEY_TO_STOP_PROGRAM):
# You can also use break
# But quit() seems to fit your specifications more
quit() 

最新更新