LoginSignup
0
0

More than 1 year has passed since last update.

sys.modulesに登録しないでモジュールをロードする方法

Posted at

sys.modulesに登録しないでモジュールをソースファイルからロードし、そのモジュールを変数にアサインして、そのモジュールの利用をその変数を通してのみの利用に限定したい場合、importlibのクラスや関数を駆使した下記の方法があるようです。参考リンク先に紹介されていました。モジュール名は識別子として利用できない文字列も付けられるようです。

import importlib.util
from importlib.machinery import SourceFileLoader
loader = SourceFileLoader("<unnamed module>", path="samplemodule.py")
spec = importlib.util.spec_from_loader(loader.name, loader)
mod = importlib.util.module_from_spec(spec)
loader.exec_module(mod)
>>> mod
<module '<unnamed module>' from 'samplemodule.py'>

参考
* https://stackoverflow.com/questions/19009932/import-arbitrary-python-source-file-python-3-3

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