开发者

Python / Tracing - How to stop a function's execution (return from it ) from within a tracer

开发者 https://www.devze.com 2023-02-03 15:19 出处:网络
Is there a way to return out of a function badfunc() using a tracer function tracer(), if we set sys.settrace(tracer).开发者_如何学GoI want to count the number of lines that badfunc() executes, and re

Is there a way to return out of a function badfunc() using a tracer function tracer(), if we set sys.settrace(tracer). 开发者_如何学GoI 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!


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 before playing with sys.settracer :)

0

精彩评论

暂无评论...
验证码 换一张
取 消