How to import a module given its name as string?

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

    Similar as @monkut 's solution but reusable and error tolerant described here http://stamat.wordpress.com/dynamic-module-import-in-python/:

    import os
    import imp
    
    def importFromURI(uri, absl):
        mod = None
        if not absl:
            uri = os.path.normpath(os.path.join(os.path.dirname(__file__), uri))
        path, fname = os.path.split(uri)
        mname, ext = os.path.splitext(fname)
    
        if os.path.exists(os.path.join(path,mname)+'.pyc'):
            try:
                return imp.load_compiled(mname, uri)
            except:
                pass
        if os.path.exists(os.path.join(path,mname)+'.py'):
            try:
                return imp.load_source(mname, uri)
            except:
                pass
    
        return mod
    

提交回复
热议问题