首页 > 解决方案 > 限制 sys.settrace() 返回的数据

问题描述

在下面的代码示例中,我得到了所有我想要的跟踪数据(跟踪permute()函数的本地值),但随后我得到了一些不需要的数据,首先是:

('call', 406, {})
('line', 407, {})
('call', 986, {'name': 'atexit', 'import_': <built-in function __import__>})

并以错误告终:

  File "<frozen importlib._bootstrap>", line 117, in __repr__
AttributeError: '_ModuleLock' object has no attribute 'name'

请问如何将输出限制为函数变量?在 Python 2 中,没有产生额外的输出。我正在使用 Python 3.8。

import sys

def trace(frame, event, arg_unused):
    print((event, frame.f_lineno, frame.f_locals))
    return trace

sys.settrace(trace)

def permute(A, P):
    n = len(A)

    # For each element of P
    for i in range(n):
        next = i

        # Check if it is already
        # considered in cycle
        while (P[next] >= 0):

            # Swap the current element according
            # to the permutation in P
            t = A[i]
            A[i] = A[P[next]]
            A[P[next]] = t

            temp = P[next]

            # Subtract n from an entry in P
            # to make it negative which indicates
            # the corresponding move
            # has been performed
            P[next] -= n
            next = temp


if __name__ == '__main__':
    A = [5, 6, 7, 8]
    P = [3, 2, 1, 0]

    permute(A, P)
    print(A)


标签: pythontrace

解决方案


我是一件小事,但意义重大:事实证明,我需要sys.settrace(None)在函数调用之后添加以避免不需要的输出。


推荐阅读