python - 如何在 Python 3 中迭代模块列表并调用它们的方法

标签 python python-3.x module

目标:能够将文件放入“模块”文件夹并从每个文件调用一组通用的方法/变量。

如果所有模块都有公共(public)方法/变量,是否应该将模块初始化为静态类?

我的项目文件夹树:

/client
    __init__.py

    /modules
        __init__.py
        foo.py
        bar.py
        spam.py

客户端__init__.py文件:

from client.modules import __all__ as moduleStrings

(get list of "modules" from "moduleStrings") # How do I write this function?

# Initialize modules dynamically
for module in modules:
    if (hasattr(module, 'init')):
        print(module.__name__)
        print("Has an initialize method!")
        module.init()

# Call the do_stuff method in each module
for module in modules:
    if (hasattr(module, 'do_stuff')):
        print("Has a do_stuff method!")
        module.do_stuff()

模块 __init__.py 文件:

# Stores a list of module string names in __all__
import os
import glob
files = glob.glob(os.path.dirname(__file__)+"/*.py")
__all__ = [ os.path.basename(f)[:-3] for f in files if "__init__" not in f]

最佳答案

您可以使用 native Python“imp”模块(https://docs.python.org/3.4/library/imp.html):

假设相同的项目树:

/client
__init__.py

/modules
    __init__.py
    foo.py
    bar.py
    spam.py

客户端init.py文件:

# -*- coding: utf-8 -*-
#!/usr/bin/python

import modules.__init__
#here you generate
modules.__init__.__load_all__()

模块init.py文件:

# -*- coding: utf-8 -*-
#!/usr/bin/python

import imp,os

def __load_all__(dir="modules"):
    list_modules=os.listdir(dir)
    list_modules.remove('__init__.py')
    for module_name in list_modules:
        if module_name.split('.')[-1]=='py':
            print "Load module ' ",module_name,"' :"
            foo = imp.load_source('module', dir+os.sep+module_name)
            foo.MyClass()

最后

模块(spam.py、bar.py、foo.py 等)文件:

# -*- coding: utf-8 -*-
#!/usr/bin/python

def __init__():
    print "load"

def MyClass():
    print "myclass spam,bar,foo, etc..."

当运行客户端__init__.py时,我们迭代模块并动态初始化它们。

关于python - 如何在 Python 3 中迭代模块列表并调用它们的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30604401/

相关文章:

python - 在 Glade 中创建可修改的 GtkScale 对象

python - 对 Python3 中特定类的实例进行赋值深复制

javascript - AngularJS,$routeProvider

python - 使用 zip 文件安装 python 模块

python - 在 Google App Engine 上使用单个 db.put() 插入多个模型实例

python csv阅读器忽略空白行

python-3.x - Python3 f 字符串 : how to avoid having to escape literal curly brackets?

Python 样式 : more concise way to rename a variable while checking it is not null

python - Tensorflow 的 Estimator.evaluate() : Is the accuracy "global" or specific to the batch it saw?

javascript - 在同一个类中调用 EventEmitter 两次?