Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A fail-safe for long-running python scripts

Tags:

python

This may be the dumbest question ever, but I'd like to know if there's a way to write a wrapper around a function (preferably a decorator) so that you can catch the internal state of the local variables in the event that an exception was raised in that function. It would catch the locals as they're created, pickle them, and then dispose of them if no exceptions were raised, or write them to file if any exceptions were found.

Is this too fanciful, or has anyone fooled around with something like this?

like image 904
BenDundee Avatar asked Nov 22 '25 19:11

BenDundee


1 Answers

You can capture the f_locals variable on a frame in the traceback:

import sys
import functools

def capturelocals(func):
    @functools.wraps(func)
    def wrapperfunc(*args, **kw):
        try:
            return func(*args, **kw)
        except Exception:
            _, _, tb = sys.exc_info()
            try:
                while tb.tb_next is not None:
                    tb = tb.tb_next  # find innermost frame
                locals = tb.tb_frame.f_locals
                print locals
            finally:
                del tb  # prevent leaking tracebacks
            raise
    return wrapperfunc

To demonstrate that it works:

>>> @capturelocals
... def foobar():
...     foo = 'bar'
...     spam = 'eggs'
...     raise ValueError('Bam!')
... 
>>> foobar()
{'foo': 'bar', 'spam': 'eggs'}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in wrapperfunc
  File "<stdin>", line 5, in foobar
ValueError: Bam!
like image 87
Martijn Pieters Avatar answered Nov 24 '25 09:11

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!