简体   繁体   中英

Importing code from a dynamically created module in Python

I have a project that tries to create a new module dynamically and then in a subsequent exec statement tries to import that module.

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"

But this throws this exception:

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

I've tried several things: adding it to sys.modules, creating a scope dict containing the name and the module as well. But no dice. I can see testmodule.testA when I do a print locals() in my exec statement, but I can't import it. What am I missing here?

Thank you.

You'll need to add your module to the sys.modules structure for import to find it:

import sys
sys.modules['testmodule.testA'] = mod

You already have the module object however and there is not much point in importing it again. mod is a reference to what Python would otherwise 'import' already .

The following would work without an import call:

mod.MyClass

If you need the module in an exec call, add it to the namespace there:

exec 'instance = MyClass()' in {'MyClass': mod.MyClass}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM