title: How to stop an infinite loop safely in Python?
body: <p>I've got a script that runs an infinite loop and adds things to a database and does things that I can't just stop halfway through, so I can't just press Ctrl+C and stop it.</p>
  <p>I want to be able to somehow stop a while loop, but let it finish it's last iteration before it stops.</p>
  <p>Let me clarify:</p>
  <p>My code looks something like this:</p>
  <pre><code>while True:
      do something
      do more things
      do more things
  </code></pre>
  <p>I want to be able to interrupt the while loop at the end, or the beginning, but not between doing things because that would be bad.</p>
  <p>And I don't want it to ask me after every iteration if I want to continue.</p>
  <hr />
  <p>Thanks for the great answers, I'm super grateful but my implementation doesn't seem to be working:</p>
  <pre><code>def signal_handler(signal, frame):
      global interrupted
      interrupted = True
  
  class Crawler():
      def __init__(self):
          # not relevant
  
      def crawl(self):
          interrupted = False
          signal.signal(signal.SIGINT, signal_handler)
          while True:
              doing things
              more things
  
              if interrupted:
                  print(&quot;Exiting..&quot;)
                  break
  </code></pre>
  <p>When I press Ctrl+C the program just keeps going ignoring me.</p>