0

我有以下界面:

class Interface(object):

    __metaclass__ = abc.ABCMeta


    @abc.abstractmethod
    def run(self):
        """Run the process."""
        return

我有一组模块都在同一个目录中。每个模块都包含一个实现我的接口的类。

例如 Launch.py​​ :

class Launch(Interface):

    def run(self):
        pass

假设我有 20 个模块,实现了 20 个类。我希望能够启动一个模块来检查某些类是否没有实现接口。

我知道我必须使用:

  • issubclass(Launch, ProcessInterface) 以了解某个类是否实现了我的流程接口。
  • 内省以获取我模块中的类。
  • 在运行时导入模块

我只是不知道该怎么做。我可以设法在模块内使用 issubclass 。但是如果我在模块之外,我不能使用 issubclass。

我需要 :

  1. 获取目录中所有模块的列表
  2. 获取每个模块中的类
  3. 在每个类上做 issubclass

我需要一个可以做到这一点的功能草案。

4

1 回答 1

0

您可能正在寻找这样的东西:

from os import listdir
from sys import path

modpath = "/path/to/modules"

for modname in listdir(modpath):
    if modname.endswith(".py"):

        # look only in the modpath directory when importing
        oldpath, path[:] = path[:], [modpath]

        try:
            module = __import__(modname[:-3])
        except ImportError:
            print "Couldn't import", modname
            continue
        finally:    # always restore the real path
            path[:] = oldpath

        for attr in dir(module):
            cls = getattr(module, attr)
            if isinstance(cls, type) and not issubclass(cls, ProcessInterface):
                # do whatever
于 2011-07-18T16:42:32.340 回答