2

我有返回给定类名的模块路径的方法

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

4

1 回答 1

2

您要查找的属性是__file__. 请注意,您可能需要在获得此值后对其进行一些按摩 - 它可能是.py, .pyc, .pyd, .so,.dll等。

当然它也将是一个完整的路径,但是你有你的根,你可以减去它以获得你关心的实际层次结构。

于 2012-07-01T09:13:20.810 回答