How to import a module given its name as string?

前端 未结 11 1391
不思量自难忘°
不思量自难忘° 2020-11-21 06:19

I\'m writing a Python application that takes as a command as an argument, for example:

$ python myapp.py command1

I want the application to

11条回答
  •  滥情空心
    2020-11-21 06:42

    Nowadays you should use importlib.

    Import a source file

    The docs actually provide a recipe for that, and it goes like:

    import sys
    import importlib.util
    
    file_path = 'pluginX.py'
    module_name = 'pluginX'
    
    spec = importlib.util.spec_from_file_location(module_name, file_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    
    # check if it's all there..
    def bla(mod):
        print(dir(mod))
    bla(module)
    

    This way you can access the members (e.g, a function "hello") from your module pluginX.py -- in this snippet being called module -- under its namespace; E.g, module.hello().

    If you want to import the members (e.g, "hello") you can include module/pluginX in the in-memory list of modules:

    sys.modules[module_name] = module
    
    from pluginX import hello
    hello()
    

    Import a package

    Importing a package (e.g., pluginX/__init__.py) under your current dir is actually straightforward:

    import importlib
    
    pkg = importlib.import_module('pluginX')
    
    # check if it's all there..
    def bla(mod):
        print(dir(mod))
    bla(pkg)
    

提交回复
热议问题