首页 > 解决方案 > 为 python 目录中的每个模块调用特定函数

问题描述

堆栈溢出的答案都没有帮助我解决这个问题: Load module from string in python

我的文件结构如下: -run.py -/boards -Brd1.py -Brd2.py -Brd3.py

我想要完成的是为板目录中的每个模块调用“运行”函数。每个模块都有这个“运行”功能。这是我在 run.py 中的代码:

import os
import sys,imp
import inspect

for item in os.listdir("boards"):
    if item.startswith("Brd") and item.endswith(".py"):
        curr_module = imp.new_module(item)
        curr_module.run()

这是我得到的错误:

AttributeError:“模块”对象没有属性“运行”

但是,当我明确地做这样的事情时:

from boards import Brd1

Brd1.run()

它完美地工作。有趣的是,代码:

import os
import sys,imp
import inspect

for item in os.listdir("boards"):
    if item.startswith("Brd") and item.endswith(".py"):
        curr_module = imp.new_module(item)
        print dir(curr_module)

只打印: ['__ doc __ ', ' __ name __ ', '__ package __ ']

反正有没有做我想要完成的事情?我要马上解决这个问题吗?

标签: pythonfileimportmodule

解决方案


这可能对您不起作用,因为正如 abarnert 指出的那样,您只是在加载一个空模块。此外,查看您的文件结构,您需要插入板文件夹的路径名:

sys.path.insert(0, './boards')

您可以通过简单地使用导入内部的 python 文档来解决您尝试的问题:https ://docs.python.org/2/library/imp.html#imp.get_suffixes

我刚刚对其进行了测试,这段代码完全符合您的要求:

for item in os.listdir("boards"):
    if item.startswith("Brd") and item.endswith(".py"):
        name = os.path.splitext(item)[0]
        fp, pathname, description = imp.find_module(name)
        with open(pathname) as f:
            curr_module = imp.load_module(name, fp, pathname, description)
            curr_module.run()

推荐阅读