,

Python – Exception and Traceback – Context and Variables


# -*- coding: utf-8 -*-
from __future__ import print_function
import time
import sys
import cPickle
from time import strftime

import inspect
import traceback

"""
Decorator Resources
http://www.ellipsix.net/blog/2010/8/more-python-voodoo-optional-argument-decorators.html
http://stackoverflow.com/questions/3931627/how-to-build-a-python-decorator-with-optional-parameters/3931903#3931903
http://typeandflow.blogspot.com/2011/06/python-decorator-with-optional-keyword.html
http://pko.ch/2008/08/22/memoization-in-python-easier-than-what-it-should-be/
http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
http://wiki.python.org/moin/PythonDecoratorLibrary#Asynchronous_Call
http://code.activestate.com/recipes/496879-memoize-decorator-function-with-cache-size-limit/
"""

def main():
    if True:
        pass
        return
    bb="ten"
    aa="wow"
    bigboy(bb, aa)
def bigboy(tima, boo):
    y = "gee man"
    fooo(y)
    trace(msg="great")
    import datetime
    print(datetime.datetime.now())
    for i in range(0,5):
        from time import sleep
        sleep(1)
        print(meo())

def fooo(x):
    #trace_inspect()
    try:
       print(1/0)
    except ZeroDivisionError as e:
       #print_exc_plus()
       print_ex()
       #frames = inspect.trace()
       #argvalues = inspect.getargvalues(frames[0][0])
       #print("Argvalues: ", inspect.formatargvalues(*argvalues))

def timing_old_old(f):
  def wrapper(*arg):
      t = time.clock()
      try:
          return f(*arg)
      finally:
          print(str(env('PATH_INFO'))+"\t"+str(f.func_name)+"\t"+str((time.clock()-t)*1000))
  return wrapper

def decoratorFunctionWithArguments(arg1=None):
    def wrap(f):
        print ("Inside wrap(arg1:"+str(arg1)+")")
        def inner_wrap(*args):
            print ("Inside wrapped_f()")
            print("Decorator arguments:"+str(arg1))
            res = f(*args)
            print (res)
            return res
        return inner_wrap
    return wrap


def print_exc_plus():
    """
    Print the usual traceback information, followed by a listing of all the
    local variables in each frame.
    """

    tb = sys.exc_info()[2]
    stack = []
    while tb:
        f = tb.tb_frame
        while f:
           stack.append(f)
           f = f.f_back
        tb = tb.tb_next
    traceback.print_exc()
    print ("Locals by frame, innermost last")
    for frame in stack:
        if frame.f_code.co_name == "": # so it does not dump globals
             continue
        print("Frame %s in %s at line %s" % (frame.f_code.co_name,
                                             frame.f_code.co_filename,
                                             frame.f_lineno))
        for key, value in frame.f_locals.items():
            strx = "\t%20s = " % key
            #We have to be careful not to cause a new error in our error
            #printer! Calling str() on an unknown object could cause an
            #error we don't want.
            try:
                strx +=str( value)
            except:
                strx += ", "
            print(strx)

#def print_ex_local():
#    import tracebackturbo as traceback
#    print(traceback.format_exc(with_vars=True))

def print_ex():
    cla, exc, exc_traceback= sys.exc_info()
    exc_args = exc.__dict__["args"] if "args" in exc.__dict__ else ""
    ex_title = cla.__name__+"exc:"+str(exc)+" - args:"+str(exc_args)
    msgs = [ex_title]
    except_location =""
    tb = traceback.extract_tb(exc_traceback)
    for filename,lineno,fn,exec_line in tb: # ('gdecorators.py', 60, 'newfoo', 'print(1/0)')
        except_location += filename+":"+str(lineno)+" - "+str(fn)+" - "+exec_line
    stacks = inspect.stack()
    for i in range(0, len(stacks)):
        stack = stacks[i]
        (first_val, filename,linenumber,module,fn,_) = stack
        linenumber  = stacks[i+1][2] if i limit:
                del dict[list.pop(0)]
        return dict[key]

def propget(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(func, doc=func.__doc__)
    else:
        doc = prop.__doc__ or func.__doc__
        prop = property(func, prop.fset, prop.fdel, doc)
    return prop

def propset(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(None, func, doc=func.__doc__)
    else:
        doc = prop.__doc__ or func.__doc__
        prop = property(prop.fget, func, prop.fdel, doc)
    return prop

def propdel(func):
    locals = sys._getframe(1).f_locals
    name = func.__name__
    prop = locals.get(name)
    if not isinstance(prop, property):
        prop = property(None, None, func, doc=func.__doc__)
    else:
        prop = property(prop.fget, prop.fset, func, prop.__doc__)
    return prop


import functools
def suppress_errors(func=None, log_func=None):
    """Automatically silence any errors that occur within a function"""
    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except Exception as e:
                if log_func is not None:
                    log_func(str(e))
        return wrapper
    if func is None:
        return decorator
    else:
        return decorator(func)


@memory(3*1000)
@timing()
def meo():
    from time import sleep
    sleep(1)
    print("hi jimmy")
    return "done meo"

if __name__ == "__main__":
    main()


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *