Search code examples
pythonterminate

Performing an action upon unexpected exit python


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 while True loop I have running, and simply saving the data each loop would be highly ineffective.

So is there a way that I can save data, say a list, when I hit the x 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.

def saveFile(list):
    print "Saving List"
    with open("file.txt", "a") as test_file:
        test_file.write(str(list[-1]))

atexit.register(saveFile(list))

That is my whole atexit part of the code and like I said, it runs fine when I set it to close through the while loop.

Is this possible, to save something when the application is terminated?


Solution

  • Your atexit usage is wrong. It expects a function and its arguments, but you're just calling your function right away and passing the result to atexit.register(). Try:

    atexit.register(saveFile, list)
    

    Be aware that this uses the list reference as it exists at the time you call atexit.register(), so if you assign to list afterwards, those changes will not be picked up. Modifying the list itself without reassigning should be fine, though.