Forum Archive

[Script release] exit.py | A sys.exitfunc replacement for Pythonista

Moe

Now because of the limitations on iOS we unfortunately can not define a cleanup function (sys.exitfunc). To accomodate for that, I've built my own module, which allows something like that in a similar manner.

import threading
from time import sleep

on_finished = None

def at_exit(f):
    if on_finished is None:
        raise NotImplementedError('on_finished must be assigned a function')
    def tmp():
        at_exit_executer = _Executed(f)
        at_exit_executer.start()
        at_exit_executer.join()
        on_finished()
    return tmp

class _Executed(threading.Thread):
    def __init__(self,function):
        super(_Executed,self).__init__()
        self.function = function
    def run(self):
        self.function()


if __name__ == '__main__':

    def end():
        print 'INSERT CLEANUP HERE'

    on_finished = end

    @at_exit
    def test():
        for x in xrange(15):
            print x
            if x == 10:
                break
        raise Exception('Cleanup should still follow after this')

    test()

You need to do 2 things: assign an exit function to on_finished and create a function after which should be cleaned up and decorate it with @at_exit

This should work for most simple scripts, however I don't know in how far this works well with scripts that are using threads themselves.

georg.viehoever

Usually, I get the same effect as at_exit() in a more structured way by using try: ... finally: ... . Any reason why you need to have something like at_exit()?

Georg

Moe

Somehow I didn't think of something that simple...