LoginSignup
19
19

More than 5 years have passed since last update.

Pythonでスクリプトを動的にimportする

Posted at

Pythonでは、 ハイフン(-) がファイル名に入ったスクリプトはimportステートメントではできません。
ですがテストを書くためにどうしてもハイフンが入ったファイル名をimportしたい場合、どうすればいいのか、調べて分かったのでメモ。

__import__

__import__ は、ファイルのパス名を引数にとり、ファイルのモジュールを返します。

load-path.py
import sys
path = sys.path
>>> module = __import__("load-path")
>>> type(module)
<type 'module'>
>>> dir(module)
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'sys', 'path']
>>> dir.path

これでハイフンがついたファイルでも、簡単にimportできます。

テストクラス内で使う

unit.test.py
import unittest

class Tester(unittest.TestCase):
    module = __import__("load-path")

    def setUp(self):
        for key in dir(self.module):
            setattr(self, key, getattr(self.module,key))
19
19
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
19
19