24
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonで実行中のファイル、関数、行番号を取得する

Last updated at Posted at 2017-07-07

python3でエラーになるので
frame = inspect.currentframe(depth + 1)から
frame = inspect.currentframe().f_backに修正


import inspect
import os

def location(depth=0):
  frame = inspect.currentframe().f_back
  return os.path.basename(frame.f_code.co_filename), frame.f_code.co_name, frame.f_lineno

def func1():
  print(location())

def main():
  print(location())
  func1()

if __name__ == '__main__':
  main()
  exit(0)
('a.py', 'main', 13)
('a.py', 'func1', 10)

参考

Python で現在のファイル名と行番号を調べる。 - kなんとかの日記 http://d.hatena.ne.jp/kwatch/20100410/1270851205

Python Tips:現在の関数の名前や引数を取得したい - Life with Python http://www.lifewithpython.com/2015/11/python-get-function-name.html

実行中の関数・メソッド名を取得したい - Qiita http://qiita.com/megmogmog1965/items/0b4ea3d58e34f1854158

24
30
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
30

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?