Python で現在のファイル名と行番号を調べる。
Python では、現在のファイル名を表す __file__ はあるけど、行番号を表す __line__ がない。現在の行番号を調べたかったら、スタックフレームオブジェクトを触る必要があるみたい。
以下がサンプルコード。__LINE__ and __FILE__ functionality in Python? - Python answers を参考に。
/tmp$ cat -n hoge.py
1 import inspect
2
3 def location(depth=0):
4 frame = inspect.currentframe(depth+1)
5 return (frame.f_code.co_filename, frame.f_lineno)
6
7 if __name__ == '__main__':
8 def f():
9 g()
10
11 def g():
12 print location() #=> ('hoge.py', 12)
13 print location(1) #=> ('hoge.py', 9)
14 print location(2) #=> ('hoge.py', 17)
15 print __file__ #=> hoge.py
16
17 f()
/tmp$ python hoge.py
('hoge.py', 12)
('hoge.py', 9)
('hoge.py', 17)