Search code examples
pythonreturnexit-code

How to abort a function manually while still returning the result in Python


In R it is possible to put on.exit(return(results_so_far)) in a function, so when a user aborts the current function (in my case in Emacs), the result will still be stored.

def myfunc():
    on.exit(return(results))
    results = []
    for i in range(1000):
        # do something
        results.append(something)
    return(results)

res = myfunc()

It means that it will be possible to run some iterations and allow the function to be cancelled manually (e.g. leave a function running overnight and immediately obtain the results gathered so far in the morning).

I have looked, but I have yet to find a solution in Python. Ideas?


Solution

  • I think you can use a try...finally clause, as in:

    def myfunc():
        try:
            results = []
            for i in range(1000):
                # do something
                results.append(something)
        finally:
            return(results)
    

    Note that the finally clause is executed whether there is an error or interrupt or not.