Skip to main content
 首页 » 编程设计

python之我如何在 python 中有一个故障安全命令

2025年05月04日16Renyi-Fan

所以我正在尝试制作一个程序,将我的鼠标随机放置在 python 的特定区域,我仍在测试它,所以它会变得有点疯狂。我想知道是否有可能制作一个故障安全命令,在输入 key 或命令时终止程序。

由于程序在我的计算机上的另一个窗口上单击并四处移动,它会取消选择 python 在其中运行的窗口,这使得“键盘中断”无法工作。

程序如下:

import pyautogui 
import random 
import time 
time.sleep(6)#gives you time to click the right window 
 
try: 
    while True:     
        x = random.randint(239, 1536)  #randomizes the position of the mouse 
 
        pyautogui.moveTo(x,663)        #moves the mouse to position 
 
        pyautogui.doubleClick()        #fires the gun in game twise    
 
        time.sleep(1)                  #gives time for the game to  
        pyautogui.doubleClick()        #catch up with the mouse and fires gun 
 
        pyautogui.doubleClick()        #fires gun twice again                                 
 
except KeyboardInterrupt: 
    print ('Yup') 

如果我的编码方式有任何问题,请告诉我。我对编码还很陌生,所以任何提示都会很棒。

请您参考如下方法:

PyAutoGUI 还具有故障安全功能。将鼠标光标移动到左上角 屏幕将导致 PyAutoGUI 引发 pyautogui.FailSafeException 异常(exception)。

您的程序可以使用 try 和 except 语句处理此异常 或者让异常使您的程序崩溃。无论哪种方式,故障安全功能都会停止 如果您尽可能快地向上和向左移动鼠标,请进行编程。

>>>import pyautogui 
>>>pyautogui.FAILSAFE= True 

默认情况下 FAILSAFE 为 True,您也可以禁用它。

>>>pyautogui.FAILSAFE = False