1# test sys.settrace with while and for loops
2
3import sys
4
5try:
6    sys.settrace
7except AttributeError:
8    print("SKIP")
9    raise SystemExit
10
11
12def print_stacktrace(frame, level=0):
13    print(
14        "%2d: %s@%s:%s => %s:%d"
15        % (
16            level,
17            "  ",
18            frame.f_globals["__name__"],
19            frame.f_code.co_name,
20            # Keep just the filename.
21            "sys_settrace_" + frame.f_code.co_filename.split("sys_settrace_")[-1],
22            frame.f_lineno,
23        )
24    )
25
26    if frame.f_back:
27        print_stacktrace(frame.f_back, level + 1)
28
29
30trace_count = 0
31
32
33def trace_tick_handler(frame, event, arg):
34    global trace_count
35    print("### trace_handler::main event:", event)
36    trace_count += 1
37    print_stacktrace(frame)
38    return trace_tick_handler
39
40
41def test_loop():
42    # for loop
43    r = 0
44    for i in range(3):
45        r += i
46    print("test_for_loop", r)
47
48    # while loop
49    r = 0
50    i = 0
51    while i < 3:
52        r += i
53        i += 1
54    print("test_while_loop", i)
55
56
57sys.settrace(trace_tick_handler)
58test_loop()
59sys.settrace(None)
60print("Total traces executed: ", trace_count)
61