按键后Python退出代码执行

2024-09-29 23:20:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想为我的游戏制作clicker,但我不知道在按下一个键后如何退出程序。我试过了

import sys

screenWidth, screenHeight = pyautogui.size()

currentMouseX, currentMouseY = pyautogui.position()



if keyboard.is_pressed("p"):
    sys.exit()

for user in range(0, 1):
        pyautogui.moveTo(849, 657)  # załóż druzyne
        pyautogui.click()
        pyautogui.PAUSE = 0.2
        pyautogui.typewrite('Bandaelo')
        pyautogui.PAUSE = 0.3
        pyautogui.moveTo(953, 742)  # potwierdź
        pyautogui.click()
        pyautogui.PAUSE = 0.4
        pyautogui.moveTo(948, 656)  # potwierdz
        pyautogui.click()
and more code like this

但它不起作用。你能帮我吗


Tags: import程序游戏sizesyspositionclickpause
2条回答

您需要导入sys对象。然后调用exit()方法停止程序

对于您的情况,您可以尝试:

import keyboard
import sys

if keyboard.is_pressed("p"):
    sys.exit()

编辑:我做了一些研究,发现在编写多线程应用程序时,raise SystemExit和sys.exit()都只终止正在运行的线程。在这种情况下,可以使用os.\u exit()退出整个过程

import os
import keyboard

if keyboard.is_pressed('p'):
   os._exit(0)

这应该可以做到,您仍然需要输入代码:

import sys
import pyautogui

def main():
    screenWidth, screenHeight = pyautogui.size()
    currentMouseX, currentMouseY = pyautogui.position()

    try:
        while 1:
            var = input("enter p to exit:  ")
            if var == 'p':
                break
            else:
                print('test something')
                # put your code here...
                # and more code like this

    except KeyboardInterrupt:
            sys.exit()
            raise

if __name__ == '__main__':
    main()

相关问题 更多 >

    热门问题