command_line.py 2.4 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
# -*- coding: UTF-8 -*-

import importlib


def dispatch(config, options, actions, targets):
    ''' 分发命令行 action '''
    action_len = len(actions)
    if action_len < 2:
        return

    index = 1
    next = targets
    action = actions[index]
    print(f"[命令路由中..]: {actions[0]}")

    while action_len >= index:
        if type(next) == type({}):
            if index == action_len:
                if next.get('run') != None:
                    print(f"[命令路由执行]:", '->'.join(actions))
                    next['run']()
                    break

            action = actions[index]
            if next.get(action) != None:
                print(f"[命令路由中..]: {action}")
                next = next[action]
                index += 1
            else:
                print("[命令路由错误]: 未找到支持的命令行路由:", '->'.join(actions))
                index += 1
        else:
            print(f"[命令路由执行]:", '->'.join(actions))

            next()
            index += 1
            break


def dispatch_runner(config, options, actions, targets):
    ''' 分发命令行 action '''
    action_len = len(actions)
    if action_len < 2:
        return

    def load_and_run(target):
        modules = target.split('.')
        class_pos = len(modules)-2
        path_pos = len(modules)-1

        if class_pos >= 0 and modules[class_pos][0].isupper():
            constructor = modules[class_pos]
            runner = modules[path_pos]
            module_path = '.'.join(modules[:class_pos])
            importlib.import_module(module_path).__getattribute__(
                constructor)(config, options).__getattribute__(runner)()
        else:
            runner = modules[path_pos]

            module_path = '.'.join(modules[:path_pos])
            importlib.import_module(module_path).__getattribute__(
                runner)(config, options)

    index = 1
    next = targets
    while action_len >= index:
        if type(next) == type({}):
            if index == action_len:
                if next.get('run') != None:
                    load_and_run(next['run'])
                    break

            action = actions[index]
            if next.get(action) != None:
                next = next[action]
                index += 1
        else:
            load_and_run(next)
            index += 1
            break