How to import a module given its name as string?

前端 未结 11 1617
不思量自难忘°
不思量自难忘° 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:45

    Note: imp is deprecated since Python 3.4 in favor of importlib

    As mentioned the imp module provides you loading functions:

    imp.load_source(name, path)
    imp.load_compiled(name, path)
    

    I've used these before to perform something similar.

    In my case I defined a specific class with defined methods that were required. Once I loaded the module I would check if the class was in the module, and then create an instance of that class, something like this:

    import imp
    import os
    
    def load_from_file(filepath):
        class_inst = None
        expected_class = 'MyClass'
    
        mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1])
    
        if file_ext.lower() == '.py':
            py_mod = imp.load_source(mod_name, filepath)
    
        elif file_ext.lower() == '.pyc':
            py_mod = imp.load_compiled(mod_name, filepath)
    
        if hasattr(py_mod, expected_class):
            class_inst = getattr(py_mod, expected_class)()
    
        return class_inst
    

提交回复
热议问题