python - 为 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 __ ']
反正有没有做我想要完成的事情?我要马上解决这个问题吗?
解决方案
这可能对您不起作用,因为正如 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()
推荐阅读
- go - 将多个 goroutine 与携带 amqp 消息的通道同步
- javascript - Redux thunk 异步操作无法访问第一个参数
- javascript - 为什么 findOneAndRemove 有时会在回调中将 null 传递给 doc?
- c# - 账本逾期计算罚款总额并加罚款
- python - Pandas group_by 保留顺序
- r - R CVXR 矩阵乘法 %*% mul_dims_promote(lh_dim, rh_dim) 中的错误:尺寸不兼容
- javascript - 从锚标记中的属性 href 加载特定 div 中的 html 文件
- pytorch - 为什么在定义 ReLU autograd 函数时需要克隆 grad_output 并将其分配给 grad_input?
- r - 如何在 R 中转换数据框并制作多个折线图?
- ios - 如何从安全区域制作自定义样式 UITableViewCell 插入?