如何从字符串中导入 Python 3 中的模块?

How to import a module in Python 3 from a string?

针对此问题的 solution 可用于 Python 2,但它使用 Python 3 中弃用的 imp 模块。

imp 已被 importlib 取代,后者适用于基于文件的导入。具体来说,importlib.import_module 需要文件名 - 而不是字符串或文件处理程序。

我通过将 URL 的内容转储到一个文件并导入它来解决这个问题

def initlog():
    modulename = '_mylogging'
    try:
        import _mylogging
    except ImportError:
        r = requests.get('http://(...)/mylogging.py')
        with open(modulename+'.py', "w") as f:
            f.write(r.text)
    finally:
        import _mylogging

    return _mylogging.MYLogging().getlogger()

但我想避免使用中间文件。

将安全性、网络性能和可用性问题放在一边 - 有没有办法将字符串提供给 importlib(或来自文件处理程序,其中如果我会使用 io.StringIO)

你可以适应exactly the same answer to 3.x, using the replacement for imp.new_module:

from types import ModuleType

foo = ModuleType('foo')

the replacement for the exec statement

foo_code = """
class Foo:
    pass
"""

exec(foo_code, globals(), foo.__dict__)

之后一切正常:

>>> dir(foo)
['Foo', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> foo.Foo()
<__main__.Foo object at 0x110546ba8>