LoginSignup
7
3

More than 5 years have passed since last update.

インポート元モジュールのパスを取得する

Posted at

理論

  • インポート時にはインポートされるモジュールのトップレベルのコードが実行される
  • インポート元はスタックトレースの一つ外側のフレーム
  • モジュールのパスはモジュールオブジェクトの __file__ 属性に入ってる

実装

main.py
import imported
imported.py
import inspect
stack = inspect.stack()
for s in stack[1:]:
    m = inspect.getmodule(s[0])
    if m:
        print(m.__file__)
        break

実行結果:

/some/where$ python -m main
/some/where/main.py
7
3
0

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
7
3