How to import a module given its name as string?

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

    You can use exec:

    exec("import myapp.commands.%s" % command)
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-21 06:53

    The below piece worked for me:

    >>>import imp; 
    >>>fp, pathname, description = imp.find_module("/home/test_module"); 
    >>>test_module = imp.load_module("test_module", fp, pathname, description);
    >>>print test_module.print_hello();
    

    if you want to import in shell-script:

    python -c '<above entire code in one line>'
    
    0 讨论(0)
  • 2020-11-21 06:57

    If you want it in your locals:

    >>> mod = 'sys'
    >>> locals()['my_module'] = __import__(mod)
    >>> my_module.version
    '2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)]'
    

    same would work with globals()

    0 讨论(0)
  • 2020-11-21 07:02

    For example, my module names are like jan_module/feb_module/mar_module.

    month = 'feb'
    exec 'from %s_module import *'%(month)
    
    0 讨论(0)
提交回复
热议问题