列出目录中的类 (Python)

Nol*_*rin 7 python directory class introspection

我正在开发一个 Python 2.6 包,我想在其中获取某个目录(包内)中所有类的列表,以便对类对象执行自省。

具体而言,如果包含当前正在执行模块的目录中有一个子目录名为“foobar的”和“foobar的”包含.py文件规定class Foo(MyBase)class Bar(MyBase)以及class Bar2,我想获得的类引用列表从对象继承MyBase,即FooBar,但不是Bar2

我不确定这个任务是否真的需要涉及文件系统的任何处理,或者子目录中的模块是否自动加载并且只需要以某种方式通过自省列出。请问这里有什么想法吗?非常感谢示例代码,因为我对 Python 非常陌生,尤其是自省。

Phi*_*ipp 8

模块永远不会自动加载,但应该很容易迭代目录中的模块并使用__import__内置函数加载它们:

import os
from glob import glob
for file in glob(os.path.join(os.path.dirname(os.path.abspath(__file__))), "*.py"):
    name = os.path.splitext(os.path.basename(file))[0]
    # add package prefix to name, if required
    module = __import__(name)
    for member in dir(module):
        # do something with the member named ``member``
Run Code Online (Sandbox Code Playgroud)

  • `glob` 仅接受一个参数,正确的循环应该是 `for file in glob(os.path.join(os.path.dirname(os.path.abspath(__file__)), "*.py"))` (3认同)

kra*_*ver 6

我想做同样的事情,这就是我最终的结果:

import glob
import importlib
import inspect
import os

current_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
current_module_name = os.path.splitext(os.path.basename(current_dir))[0]
for file in glob.glob(current_dir + "/*.py"):
     name = os.path.splitext(os.path.basename(file))[0]

     # Ignore __ files
     if name.startswith("__"):
         continue
     module = importlib.import_module("." + name,package=current_module_name)

     for member in dir(module):
         handler_class = getattr(module, member)

         if handler_class and inspect.isclass(handler_class):
             print member
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你..


cul*_*rón 5

选项 1:使用 -r 参数 grep 查找“^class (\a\w+)\(Myclass”正则表达式。

选项 2:将目录作为包(创建一个空的 __init__.py 文件),导入它并递归地迭代其成员:

import mymodule
def itermodule(mod):
    for member in dir(mymod):
        ...

itermodule(mymodule)
Run Code Online (Sandbox Code Playgroud)