python 动态调用模块内的函数

来源:互联网 发布:唯美现代诗 知乎 编辑:程序博客网 时间:2024/06/07 04:49

场景

程序在运行的过程中,根据变量或者动态配置决定导入哪个模块的函数。

实现

1.同一个路径利用 getattr 动态调用函数:main.py 与 third_buy.py在同一个路径下

# third_buy中有N个***_func(params)函数import third_buythird_method = '%s_func' % method# 通过函数名的字符串来调用这个函数res = getattr(third_buy, third_method)(params)

2.跨了文件夹利用 importlib 动态调用文件和函数,目录结构如:

.├── bill│   ├── dingxin.py│   ├── __init__.py├── flow│   ├── __init__.py│   └── xunzhong.py├── __init__.py├── server.py
import importlib# business 为业务类型:flow, bill# method 为文件名:dingxin, xunzhongmethod = '{0}.{1}'.format(business, method)module = importlib.import_module(method)buy_res = module.func(params)
原创粉丝点击