在Python 3中查找上下文的开始和结束

时间:2019-04-29 14:55:26

标签: python python-3.x python-2.7 abstract-syntax-tree python-3.7

我试图找到上下文开头和结尾的行号。在Python 2.7 中,我可以成功完成以下操作:

1 from contextlib import contextmanager
2 import sys
3
4 @contextmanager
5 def print_start_end_ctx():
6     frame = sys._getframe(2)
7     start_line = frame.f_lineno
8     yield
9     end_line = frame.f_lineno
10    print("start_line={}\nend_line={}".format(start_line, end_line))
11 
12 with print_start_end_ctx():
13     100
14     (200,
15      300)

Python 2.7 中的输出:

start_line=12
end_line=15

但是,在 Python 3.7 中从frame对象提取行号失败:

start_line=12
end_line=14

0 个答案:

没有答案