简体   繁体   English

如何从Python生成器对象获取源行号?

[英]How to get source line number from a Python generator object?

Here is an example: 这是一个例子:

def g():
  yield str('123')
  yield int(123)
  yield str('123')

o = g()

while True:
  v = o.next()
  if isinstance( v, str ):
    print 'Many thanks to our generator...'
  else:
    # Or GOD! I don't know what to do with this type
    raise TypeError( '%s:%d Unknown yield value type %s.' % \
                     (g.__filename__(), g.__lineno__(), type(v) )
                   )

How do I get the source file name and the exact yield line number, when my generator returns unknown type (int in this example)? 当我的生成器返回未知类型(在此示例中为int)时,如何获取源文件名和确切的收益行号?

Your generator object "o" in this case has all the information you want. 在这种情况下,生成器对象“ o”具有所需的所有信息。 You can paste your example into a Python console, and inspect with dir both the function "g" and the generator "o". 您可以将示例粘贴到Python控制台中,并使用dir检查函数“ g”和生成器“ o”。

The generator has the attributes "gi_code" and "gi_frame" which contain the information you want: 生成器具有属性“ gi_code”和“ gi_frame”,其中包含所需的信息:

>>> o.gi_code.co_filename
'<stdin>'
# this is the line number inside the file:
>>> o.gi_code.co_firstlineno
1
# and this is the current line number inside the function:
>>> o.gi_frame.f_lineno
3

I don't think you can get the information you want. 我认为您无法获得所需的信息。 That's the sort of thing captured in exceptions, but there has been no exception here. 这就是在异常中捕获的东西,但是这里没有例外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM