新しいモジュールを動的に作成しようとするプロジェクトがあり、その後のexec
ステートメントでそのモジュールをインポートしようとします。
import imp
s="""
class MyClass(object):
def __init__(self):
pass
def foo(self):
pass
"""
mod = imp.new_module("testmodule.testA")
exec s in mod.__dict__
exec "import testmodule.testA"
しかし、これはこの例外をスローします:
Traceback (most recent call last):
File "test.py", line 14, in <module>
exec "import testmodule.testA"
File "<string>", line 1, in <module>
ImportError: No module named testmodule.testA
私はいくつかのことを試しました: sys.modules に追加しscope
、名前とモジュールを含む dict を作成します。しかし、サイコロはありません。print locals()
ステートメントで a を実行すると、testmodule.testA が表示されますexec
が、インポートできません。ここで何が欠けていますか?
ありがとうございました。