限制sys.settrace()返回的数据 [英] limit data returned by sys.settrace()

查看:0
本文介绍了限制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'

我如何才能将输出限制为仅函数变量?在Python2中,没有产生额外的输出。我使用的是Python3.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)


推荐答案

我是一个小东西,但意义重大:原来我需要在函数调用后添加sys.settrace(None)以避免不需要的输出。

这篇关于限制sys.settrace()返回的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆