title: Performing an action upon unexpected exit python
body: <p>I was wandering if there was a way to perform an action before the program closes. I am running a program over a long time and I do want to be able to close it and have the data be saved in a text file or something but there is no way of me interfering with the <code>while True</code> loop I have running, and simply saving the data each loop would be highly ineffective. </p>
  
  <p>So is there a way that I can save data, say a list, when I hit the <code>x</code> or destroy the program? I have been looking at the atexit module but have had no luck, except when I set the program to finish at a certain point.</p>
  
  <pre><code>def saveFile(list):
      print "Saving List"
      with open("file.txt", "a") as test_file:
          test_file.write(str(list[-1]))
  
  atexit.register(saveFile(list))
  </code></pre>
  
  <p>That is my whole <code>atexit</code> part of the code and like I said, it runs fine when I set it to close through the <code>while loop</code>. </p>
  
  <p>Is this possible, to save something when the application is terminated?</p>