我正在尝试构建一个可模糊的应用程序,因此我需要一种方法,允许我在不修改主应用程序的情况下创建新模块。要做到这一点,我正在准备允许我从文件夹导入所有模块的模块系统,并且我想通过使用类属性来选择要使用的模块。
模块:
topology_O.py
:
class Topology(object):
def __init__(self):
self.name = 'O'
self.version = 0.1
def __str__(self):
string = "Topology: " + self.name
string += "Version: " + str(self.version)
return string
topology_H.py
:
class Topology(object):
def __init__(self):
self.name = 'H'
self.version = 0.1
def __str__(self):
string = "Topology: " + self.name
string += "\n > Version: " + str(self.version)
return string
我想像这样使用它们:
myTopology = some_topology_thing('O')
print myTopology
# Topology: O
# > Version: 0.1
myTopology = some_topology_thing('H')
print myTopology
# Topology: H
# > Version: 0.1
因此,name
将选择和使用这些模块。
答案 0 :(得分:4)
importlib可以在这里提供帮助:
import importlib
def some_topology_thing(topo_type):
mod = importlib.import_module('topology_{}'.format(topo_type))
return mod.Topology()
答案 1 :(得分:1)
我自己的解决方案
import os
import imp
from glob import glob
def some_topology_thing(topology):
topologys = {}
module_path = os.path.join(os.path.dirname(__file__), '..', 'topologys')
modules = glob(module_path + '/*.py')
for i in modules:
foo = imp.load_source('', i)
topologys.update({foo.Topology().name: i})
try:
return imp.load_source('', topologys[topology]).Topology()
except ImportError:
print "Error: no topology \'" + topology + "\' Found"
print "Available topologys are: " + str(topologys.keys())