0

I want to make clicker for my game and i don't know how can I exit program after I press a key. I've tried

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

but it doesn't work. Can You help me?

EnTryN
  • 1
  • 2
  • Does this answer your question? [How to exit a Python program or loop via keybind or macro? Keyboardinterrupt not working](https://stackoverflow.com/questions/52756289/how-to-exit-a-python-program-or-loop-via-keybind-or-macro-keyboardinterrupt-not) – dboy May 03 '20 at 13:01
  • Where do I put my code? – EnTryN May 04 '20 at 16:20

2 Answers2

0

This should do the trick, you still need to put your code:

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()
dboy
  • 1,004
  • 2
  • 16
  • 24
  • When I run script it says to "enter p to exit" but my code doesn't run. I need to enter other key than p to run my script. I need to pause script at certain point not at the beggining – EnTryN May 03 '20 at 14:15
-1

You need to import sys object. Then call the exit() method to stop your program.

For your case you can try:

import keyboard
import sys

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

EDIT : I have done a little research and find when writing a multithreaded app, raise SystemExit and sys.exit() both terminates only the running thread. In this case, you can use os._exit() which exits the whole process.

import os
import keyboard

if keyboard.is_pressed('p'):
   os._exit(0)
  • 1
    In this case, there will be literally no difference between `sys.exit()` and `exit()`, so there's not too much point in using `sys` module – Alex.Kh May 02 '20 at 21:57
  • You can check https://stackoverflow.com/questions/73663/how-to-terminate-a-python-script – Bahadır Çetin May 02 '20 at 22:00
  • I think your problem is related to catching key press. Did you debug it? I mean is it enter the if condition when you press 'p'? – Bahadır Çetin May 03 '20 at 01:17