Skip to content
Advertisement

In Python code below, how can I immediately exit the code?

I have been trying below this two days, but cannot make it work.

I have tried

except KeyboardInterrupt:
sys.exit()
exit()
control+C

, and so on.

I have tried the code, but it terminates only after 30 seconds or 1 minute. It seems like “listener” in the code makes the code complicated.

I need to make the code terminate immediately when I press ESC. “Terminate” here means stop the code from running or close the entire terminal. Either way is fine, but it needs to work “immediately”.

I am using Windows10. It does not need to be compatible with MAC os.

import pydirectinput
import datetime
import time
import threading
from pynput.mouse import Controller, Button
from pynput.keyboard import Listener, KeyCode
TOGGLE_KEY = KeyCode(char="`")
clicking = False
mouse = Controller()

def clicker():    
    global fishpause
    global a_press
    global d_press
    global maxtime
    duration = 0
    while True and duration <= maxtime:
        qtime = datetime.datetime.utcnow()
        if qtime.hour == 11 and qtime.minute == 30: 
            print("Quiting by using an error...")
            pydirectinput.keydown('alt')                
        else:
            if clicking:
                mouse.press(Button.right)
                #print("Button pressed")
                goleft(fishpause, a_press)
                duration += 1
                print(f"Duration is: {duration}")
                time.sleep(0.5)
        time.sleep(0.5)
        mouse.release(Button.right)
    
def toggle_event(key):
    if key == TOGGLE_KEY:
        global clicking
        clicking = not clicking
        print("Clicking changed")

def goleft(fishpause, a_press):
    pydirectinput.press('a', presses=1, interval=a_press)
    print("Moving left")
    pydirectinput.PAUSE = fishpause
    print(f"PAUSING: {fishpause}")
  
maxtime = 4500
fishpause = 9.0 
a_press = 0.1 
time.sleep(1)
print("Starting")
pydirectinput.press('esc', presses=1, interval=0.1)
click_thread = threading.Thread(target=clicker)
click_thread.start()
time.sleep(3)
with Listener(on_press=toggle_event) as listener:
    listener.join()

Advertisement

Answer

The program won’t exit while the click_thread is still running. If the clicker knows that it’s supposed to exit it can break the loop and return. Alternatively, if you mark the thread as a daemon:

click_thread = threading.Thread(target=clicker, daemon=True)

then it will exit when the main program exits.

You can test this with the tiny program below. Try with daemon=True and with daemon=None:

import threading
import time

def thread_loop():
    while True:
        print("!");
        time.sleep(.5)

if __name__ == '__main__':
    bkgnd = threading.Thread(target=thread_loop, daemon=True)
    bkgnd.start()
    print("exit main")
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement