Python / Tracing - How to stop a function's execution (return from it ) from within a tracer
Question: Is there a way to return out of a function badfunc() using a tracer function
tracer(), if we set sys.settrace(tracer). I want to count the number of lines
that badfunc() executes, and return out of it if it executes more than a given
amount of lines.

e.g:

    
    
    def badfunc():
        while True:
          import time
          time.sleep(1)
    
    def tracer(*args):
        counter += 1
        if counter > MAX_NUMLINES:
            return_from_badfunc()
        return tracer
    
    sys.settrace(tracer)
    

Thanks!


Answer: Something like this maybe:

    
    
    import sys
    
    MAX_NUMLINES = 7
    counter = 0
    
    class TooMuchLine(Exception):
        pass
    
    def tracer(frame, event, arg):
        global counter
        if event == "line":
            counter += 1
            print "counter", counter
            if counter > MAX_NUMLINES:
                 raise TooMuchLine()
    
        return tracer
    
    def badfunc():
        while True:
          import time
          time.sleep(1)
    
    
    sys.settrace(tracer)
    
    print 'start'
    
    try:
       badfunc()
    except TooMuchLine:
       print 'stopped'
    
    print 'done'
    

Output:

    
    
    start
    counter 1
    counter 2
    counter 3
    counter 4
    counter 5
    counter 6
    counter 7
    counter 8
    stopped
    done
    

N.B: I hope that you already read
[this](http://stackoverflow.com/questions/1692866/what-cool-hacks-can-be-done-
using-sys-settrace/1693108#1693108) before playing with sys.settracer :)

