Python 如何找到要导入到其他文件中的类的完整模块路径
我有一个方法返回给定类名的模块路径Python 如何找到要导入到其他文件中的类的完整模块路径,python,path,Python,Path,我有一个方法返回给定类名的模块路径 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]
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)
def findModulePath(路径,类名):
属性=[]
对于os.walk(路径)中的根、目录和文件:
对于源in(如果s.endswith(“.py”):
name=os.path.splitext(os.path.basename(源))[0]
全名=os.path.splitext(源)[0]。替换(os.path.sep,“.”)
m=imp.load_模块(完整名称,*imp.find_模块(名称,[root]))
尝试:
attr=getattr(m,类名)
attributes.append(attr)
#如果属性模块中的“.”
#返回
除:
通过
如果len(attributes)您要查找的属性是\uuuu文件\uuu
。注意:获取该值后,您可能需要对其进行一些处理-它可能是一个.py
,.pyc
,.pyd
,.so
,.dll
,等等
当然它也是一个完整的路径,但是你有根,你可以减去根来得到你关心的实际层次结构。我已经替换了文件中的基本包路径,然后替换为/。