python - 限制 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)
解决方案
我是一件小事,但意义重大:事实证明,我需要sys.settrace(None)
在函数调用之后添加以避免不需要的输出。
推荐阅读
- javascript - 类型错误:.json WEBPACK_IMPORTED_MODULE_2__.filter 不是函数
- assembly - 将局部变量与 16 字节边界对齐 (x86 asm)
- python - 使用 xlsxwriter 合并每隔一个单元格
- javascript - 使用p5.js,在draw中使用函数时,如何让它只运行一次?
- python - 对于大小为 10 的轴 1,索引 243 超出范围
- java - 数据库错误:“NullPointerException:尝试在空对象引用上调用虚拟方法 getApplicationInfo()...”
- java - 尝试获取资源的路径导致 NullPointerExceptions
- c - 在 C 中传递链表时如何解决这些冲突类型错误?
- python-3.x - Python:仅删除方括号并保持原样
- shell - 在第 2 列中查找第 1 列中选择的概率