You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何动态执行sub_folder2下所有Python脚本的函数并封装到run_all_functions.py

实现方案解答

完全可以实现,以下是两种可直接落地的方案,新增脚本时不需要修改run_all_functions.py的核心逻辑:


方案1:使用importlib动态导入模块 + 遍历成员

核心思路是先遍历sub_folder2下的所有.py文件,动态导入每个模块后过滤出模块内定义的函数执行即可。

代码实现(写在run_all_functions.py中)

import os
import importlib
import inspect
import sys

# 定位sub_folder2路径,把项目根目录加入模块搜索路径
current_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(current_dir)
sub_folder2_path = os.path.join(root_dir, "sub_folder2")
sys.path.append(root_dir)

for filename in os.listdir(sub_folder2_path):
    # 只处理有效Python脚本,跳过__init__.py和其他非脚本文件
    if filename.endswith(".py") and filename != "__init__.py":
        module_name = f"sub_folder2.{filename[:-3]}"
        # 动态导入对应模块
        module = importlib.import_module(module_name)
        # 遍历模块所有成员
        for name, member in inspect.getmembers(module):
            # 只执行当前模块定义的函数,排除导入的函数、内置方法等
            if inspect.isfunction(member) and member.__module__ == module_name:
                print(f"执行函数:{module_name}.{name}")
                # 函数有统一入参的话可以在这里统一传参
                member()

适用场景

  • 不需要提前约定函数命名规则
  • 仅run_all_functions.py需要用到sub_folder2的函数,不需要全局导出

方案2:在sub_folder2的__init__.py中自动导出所有模块

核心思路是修改sub_folder2的初始化文件,让它自动导入当前目录下的所有.py模块和模块内的函数,run_all_functions只需要导入sub_folder2包就能遍历所有函数。

第一步:修改sub_folder2/init.py内容

import os
import importlib
import inspect

for filename in os.listdir(os.path.dirname(__file__)):
    if filename.endswith(".py") and filename != "__init__.py":
        module_name = filename[:-3]
        # 相对路径导入当前包下的模块
        module = importlib.import_module(f".{module_name}", __name__)
        # 把模块内所有函数导出到当前包的命名空间
        for name, member in inspect.getmembers(module):
            if inspect.isfunction(member) and member.__module__ == module.__name__:
                globals()[name] = member

第二步:run_all_functions.py中的代码

import inspect
import sys
import os

# 把项目根目录加入搜索路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from sub_folder2 import *

for name, member in inspect.getmembers(sys.modules[__name__]):
    if inspect.isfunction(member) and member.__module__.startswith("sub_folder2"):
        print(f"执行函数:{name}")
        member()

适用场景

  • 项目内多个地方需要调用sub_folder2下的函数,统一导出后调用更方便

注意事项

  • 如果函数有入参要求,需要提前约定统一的入参规则,否则执行时会报错
  • 如果存在不需要执行的函数,可以加自定义装饰器标记,遍历时跳过对应标记的函数即可
  • 建议加异常捕获逻辑,避免单个函数执行失败打断整个执行流程

内容的提问来源于stack exchange,提问作者KKCH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 19:45:04