I'm on Pythonista 3 and atexit.register on its own doesn't quite work - running sys.exit will call the registered atexit function but forcibly terminating the program (via the stop button) doesn't do that.

Using a try..finally like this, worked, though:

@atexit.register def _exitcb(): print('Exit') try: # Do stuff finally: exit()

I'm not sure if that's how it would normally work on a computer running Python but that's just a tiny tidbit of hopefully helpful information for anyone coming across this issue.