導入類的完整模塊路徑我有方法,返回給定的類名稱的模塊路徑如何找到在其他文件
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