我有返回给定类名的模块路径的方法
def findModulePath(path, className):
attributes = []
for root, dirs, files in os.walk(path):
for source in (s for s in files if s.endswith(".py")):
name = os.path.splitext(os.path.basename(source))[0]
full_name = os.path.splitext(source)[0].replace(os.path.sep, '.')
m = imp.load_module(full_name, *imp.find_module(name, [root]))
try:
attr = getattr(m, className)
attributes.append(attr)
# if "." in attr.__module__:
# return
except:
pass
if len(attributes) <= 0:
raise Exception, "Class %s not found" % className
for element in attributes:
print "%s.%s" % (element.__module__, className)
但它不返回模块的完整路径,例如我在对象包中有一个名为“objectmodel”的python文件,它包含一个模型类,所以我调用findModulePath(MyProjectPath,"Model")。它打印 objectmodel.Model 但我需要 objects.objectmodel.Model