[elbe-devel] [PATCH] elbepack: main: implement central CLI dispatch in argparse
Thomas Weißschuh
thomas.weissschuh at linutronix.de
Tue Jul 30 11:45:49 CEST 2024
The code is shorter and it is easier to extend with global arguments.
Signed-off-by: Thomas Weißschuh <thomas.weissschuh at linutronix.de>
---
elbepack/main.py | 34 +++++++++-------------------------
1 file changed, 9 insertions(+), 25 deletions(-)
diff --git a/elbepack/main.py b/elbepack/main.py
index 431e1c4b3a24..92a8a501497c 100644
--- a/elbepack/main.py
+++ b/elbepack/main.py
@@ -2,6 +2,7 @@
# SPDX-License-Identifier: GPL-3.0-or-later
# SPDX-FileCopyrightText: 2013-2017 Linutronix GmbH
+import argparse
import importlib
import pkgutil
import sys
@@ -14,36 +15,19 @@ def get_cmdlist():
return [x for _, x, _ in pkgutil.iter_modules(elbepack.commands.__path__)]
-def usage():
- print('elbe v%s' % elbe_version)
- print("need a subcommand: e.g. \'elbe initvm\'. \n\
- Available subcommands are: \n")
- for i in get_cmdlist():
- print(' * %s' % i)
-
-
def main(argv=sys.argv):
- # with python -melbepack the optparse usage message would show __main__.py
- if argv[0].endswith('__main__.py'):
- argv[0] = 'elbe'
-
- if len(argv) < 2:
- usage()
- sys.exit(20)
+ parser = argparse.ArgumentParser(prog='elbe')
+ parser.add_argument('--version', action='version', version=f'%(prog)s v{elbe_version}')
- if argv[1] == '--version':
- print('elbe v%s' % (elbe_version))
- sys.exit(0)
+ subparsers = parser.add_subparsers(required=True, dest='cmd')
- cmd_list = get_cmdlist()
+ for cmd in get_cmdlist():
+ subparsers.add_parser(cmd)
- if argv[1] not in cmd_list:
- print('Unknown subcommand !\n')
- usage()
- sys.exit(20)
+ args, cmd_argv = parser.parse_known_args(argv[1:])
- modname = 'elbepack.commands.' + argv[1]
+ modname = 'elbepack.commands.' + args.cmd
cmdmod = importlib.import_module(modname)
- cmdmod.run_command(argv[2:])
+ cmdmod.run_command(cmd_argv)
---
base-commit: dcec7a10e0a4d63c7ee6c3d6077482ab98113211
change-id: 20240730-argparse-dispatch-e31a0f226b4b
Best regards,
--
Thomas Weißschuh <thomas.weissschuh at linutronix.de>
More information about the elbe-devel
mailing list