How to import a module given its name as string?

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

    The following worked for me:

    import sys, glob
    sys.path.append('/home/marc/python/importtest/modus')
    fl = glob.glob('modus/*.py')
    modulist = []
    adapters=[]
    for i in range(len(fl)):
        fl[i] = fl[i].split('/')[1]
        fl[i] = fl[i][0:(len(fl[i])-3)]
        modulist.append(getattr(__import__(fl[i]),fl[i]))
        adapters.append(modulist[i]())
    

    It loads modules from the folder 'modus'. The modules have a single class with the same name as the module name. E.g. the file modus/modu1.py contains:

    class modu1():
        def __init__(self):
            self.x=1
            print self.x
    

    The result is a list of dynamically loaded classes "adapters".

提交回复
热议问题