【问题标题】:How to find column number in Python code如何在 Python 代码中查找列号
【发布时间】:2014-04-13 15:57:25
【问题描述】:

小问题:当提到here 中调用的函数时,我可以找到行号

同样,我怎样才能找到列号?

长问题:

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 究竟带来了什么。

【问题讨论】:

  • 你能准确地写出每个示例打印的内容吗?
  • 第一个是伪代码,我为第二个添加了输出。

标签: python


【解决方案1】:

the official documentation 可以看出,它确实返回了字节码中最后一个执行字节的索引。那基本上是专栏,但不是在源代码中,而是在字节码中。您可以通过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在编译后保留字节码和列之间的映射。如果我是对的,基本上不可能得到列号。

【讨论】:

  • 字节码中的列号足以满足我的目的。
猜你喜欢
  • 2014-01-13
  • 2013-08-06
  • 2016-05-11
  • 2013-08-07
  • 1970-01-01
  • 1970-01-01
  • 2011-04-21
  • 1970-01-01
相关资源
最近更新 更多