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

Mal*_*zar 2 python

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

由于该程序在我计算机上的另一个窗口上单击并移动,它取消了 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')
Run Code Online (Sandbox Code Playgroud)

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

R__*_*i__ 10

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

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

>>>import pyautogui
>>>pyautogui.FAILSAFE= True
Run Code Online (Sandbox Code Playgroud)

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

>>>pyautogui.FAILSAFE = False
Run Code Online (Sandbox Code Playgroud)


idj*_*jaw 5

您要做的是在您的异常中使用sys.exit()

尝试这个:

import sys

try:
    # all your code
except KeyboardInterrupt:
    sys.exit()
Run Code Online (Sandbox Code Playgroud)