如何在Python代码中找到列号
简短的问题:我可以找到函数被调用时的行号,像在这里提到的那样。
那么,我该如何找到列号呢?
长问题:
def col():
return something
print("result", col(), col(), col())
应该返回不同的数字,每次调用这个打印函数时返回相同的数字。
我该如何做到这一点?
编辑:
我现在的解决方法如下:
import inspect
def cid():
f = inspect.currentframe().f_back
caller_id = (f.f_lineno, f.f_lasti)
return caller_id
print((cid(), cid(), cid(), cid(), cid()))
print((cid(), cid(), cid(), cid(), cid()))
print((cid(), cid(), cid(), cid(), cid()))
print((cid(), cid(), cid(), cid(), cid()))
print((cid(),
cid(),
cid(),
cid(),
cid()))
目前运行正常。这会打印:
((8, 30), (8, 36), (8, 42), (8, 48), (8, 54))
((9, 65), (9, 71), (9, 77), (9, 83), (9, 89))
((10, 100), (10, 106), (10, 112), (10, 118), (10, 124))
((11, 135), (11, 141), (11, 147), (11, 153), (11, 159))
((13, 170), (14, 176), (15, 182), (16, 188), (17, 194))
问题是:我不知道 f_lasti 在某一时刻到底带来了什么。
1 个回答
2
从官方文档可以看到,它确实返回了在字节码中最后执行的字节的索引。这基本上是指列的位置,但不是在源代码中,而是在字节码中。你可以通过dis.dis()
来查看代码的反汇编,这样就能理解f_lasti
中的值是怎么回事:
import inspect
import dis
def cid():
f = inspect.currentframe().f_back
dis.dis(f.f_code)
caller_id = (f.f_lineno, f.f_lasti)
return caller_id
print((cid(), cid(), cid(), cid(), cid()))
我觉得Python在编译后并不会保留字节码和列之间的对应关系。如果我没猜错的话,基本上是不可能获取到列号的。