Stopping the execution of Python script

Viewed 1995

I have written this question after reading this question and this other one. I would like to stop the execution of a Python script when a button is pressed. Here the code:

import turtle
from sys import exit

def stop_program():
    print("exit function")
    exit(0) #raise SystemExit(0) gives the same result
    print("after the exit function")

# Create keyboard binding
turtle.listen()
turtle.onkey(stop_program, "q")

# Main function
while True:
    # Code: everything you want

If I press the button "q" (even muliple time) the output is:

exit function
exit function
exit function
exit function
exit function
exit function
exit function
...

i.e. one line every time I press. This means that the exit works for the function and not for the whole program. Any suggestion?

2 Answers

Dont use the while loop, use turtle.mainloop()

import turtle
from sys import exit

def stop_program():
    print("exit function")
    exit(0) #raise SystemExit(0) gives the same result
    print("after the exit function")

# Create keyboard binding
turtle.listen()
turtle.onkey(stop_program, "q")


turtle.mainloop()

That seems to work fine for me, give it a try.

Try to use: sys.exit(), see if that works. Below code worked for me.

import turtle
import sys

def stop_program():
 print("exit function")
 sys.exit() #raise SystemExit(0) gives the same result
 print("after the exit function")


 # Create keyboard binding
 turtle.listen()
 turtle.onkey(stop_program, "q")
 turtle.mainloop()
Related