导入类的完整模块路径我有方法,返回给定的类名称的模块路径如何找到在其他文件
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文件,它包含一个Model类,所以我调用findModulePath(MyProjectPath,“Model”)。它打印objectmodel.Model,但我需要objects.objectmodel.Model
我已经替换__file__中的基础包路径,然后替换/ with。 – Pooya