本文链接:https://www.cnblogs.com/tujia/p/14468242.html

 

一、原理

1)sys.path 添加环境变量目录

sys.path.append(<dir_name>)

2)__import__ 函数导入模块

_module = __import__(<module_name>)

3)getattr 获取类

getattr(<module_name>, <class_name>)

注:如果需要实例化类的话,后面加个括号:getattr(<module_name>, <class_name>)()

 

二、实例

说明:加载 tasks 目录里的所以类,并执行 run 方法

import sys
import pathlib
from tools import istring

sys.path.append('tasks')


def run(task):
    items = []
    if task != '':
        _module = __import__(task)
        _class = istring.ucwords(task)
        items.append(getattr(_module, _class)())
    else:
        for x in pathlib.Path('tasks').iterdir():
            if x.name == '__pycache__':
                continue
            _module = __import__(x.stem)
            _class = istring.ucwords(x.stem)
            items.append(getattr(_module, _class)())

    for task in items:
        task.run()


if __name__ == '__main__':
    task = sys.argv[1] if len(sys.argv) == 2 else ''
    run(task)

注:istring 是我自己写的助手类,这个需要按自己的类命名规则处理一下 ~

 

本文链接:https://www.cnblogs.com/tujia/p/14468242.html


完。

 

相关文章:

  • 2022-02-23
  • 2022-12-23
  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-25
  • 2022-02-04
  • 2022-12-23
  • 2021-05-17
  • 2021-05-09
相关资源
相似解决方案