title: Stopping the execution of Python script
body: <p>I have written this question after reading <a href="https://stackoverflow.com/questions/543309/programmatically-stop-execution-of-python-script/543375">this question</a> and <a href="https://stackoverflow.com/questions/73663/terminating-a-python-script">this other one</a>.
  I would like to stop the execution of a Python script when a button is pressed. Here the code:</p>
  
  <pre><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
  </code></pre>
  
  <p>If I press the button "q" (even muliple time) the output is:</p>
  
  <pre><code>exit function
  exit function
  exit function
  exit function
  exit function
  exit function
  exit function
  ...
  </code></pre>
  
  <p>i.e. one line every time I press.
  This means that the <code>exit</code> works for the function and not for the whole program. Any suggestion?</p>