Last active
September 22, 2023 23:37
-
-
Save perryism/a1391ccd1df8be462133cf41f82f8272 to your computer and use it in GitHub Desktop.
This little class can help create command line toolbox easily.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import logging | |
from enum import EnumMeta | |
logger = logging.getLogger(__name__) | |
class Blackmore: | |
def __init__(self, name, functions): | |
self.name = name | |
self.functions = dict([[f.__name__, f] for f in functions]) | |
def execute(self): | |
parser = argparse.ArgumentParser(prog = self.name) | |
parser.add_argument("cmd", help="command", choices=self.functions.keys()) | |
args = parser.parse_known_args() | |
cmd_name = args[0].cmd | |
function = self.functions[cmd_name] | |
args = self.get_args(parser, function) | |
params = {} | |
for k, v in function.__annotations__.items(): | |
params[k] = getattr(args, k) | |
return function(*params.values()) | |
def get_args(self, parser, function): | |
for k, v in function.__annotations__.items(): | |
if v is str: | |
parser.add_argument(k, help=k) | |
elif isinstance(v, EnumMeta): | |
parser.add_argument(k, help=k, choices=v.__members__.keys()) | |
else: | |
raise TypeError("Only support str") | |
return parser.parse_args() | |
def hello(name: str): | |
print(f"hello {name}") | |
from enum import Enum | |
class Color(Enum): | |
RED= "red" | |
BLUE = "blue" | |
def choose_color(color: Color): | |
print(f"color {color} is chosen") | |
blackmore = Blackmore("My Commands", [hello, choose_color]) | |
blackmore.execute() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment