Python动态加载模块

通过动态加载模块给方便给telegram机器人添加功能。

首先遍历mods目录下指定文件(这里用的glob来匹配文件名),再通过__import__函数导入,需要注意的是fromlist这个参数。

The fromlist  should be a list of names to emulate ``from name import ...'', or an empty list to emulate ``import name''.

意思是此处不加这个参数就会导入mods,否则导入mods.*。

1
2
3
4
5
6
7
8
9
10
11
12
# coding: utf-8
import glob
import os.path

MOD_PATH = 'mods'

mod_handlers = []
files = glob.glob(MOD_PATH + '/[a-z]*.py')
for filename in files:
module_name, ext = os.path.splitext(os.path.basename(filename))
module = __import__('{}.{}'.format(MOD_PATH, module_name), fromlist=['*'])
mod_handlers.append(module.handler)

参考

https://pythoncaff.com/docs/pymotw/glob-file-name-rule-matching/110
https://stackoverflow.com/questions/31720874/import-arbitrary-subdirectory-modules

0%