[elbe-devel] [PATCH 11/19] elbepack: add: migrate to argparse

Thomas Weißschuh thomas.weissschuh at linutronix.de
Tue Jul 9 09:23:44 CEST 2024


argparse has various advantages over optparse:

* Autogenerated command synopsis.
* Required arguments.
* Flexible argument types.
* Subparsers.

Furthermore optparse is deprecated since Python 3.2 (2011).

Signed-off-by: Thomas Weißschuh <thomas.weissschuh at linutronix.de>
---
 elbepack/commands/add.py | 17 +++++++----------
 1 file changed, 7 insertions(+), 10 deletions(-)

diff --git a/elbepack/commands/add.py b/elbepack/commands/add.py
index d726aa569bb4..5e748edce354 100644
--- a/elbepack/commands/add.py
+++ b/elbepack/commands/add.py
@@ -2,25 +2,22 @@
 # SPDX-License-Identifier: GPL-3.0-or-later
 # SPDX-FileCopyrightText: 2016-2017 Linutronix GmbH
 
+import argparse
 import sys
-from optparse import OptionParser
 
 from elbepack.elbexml import ElbeXML, ValidationError
 
 
 def run_command(argv):
 
-    oparser = OptionParser(
-        usage='usage: %prog add [options] <xmlfile> <pkg1> [pkgN]')
-    (_, args) = oparser.parse_args(argv)
+    aparser = argparse.ArgumentParser(prog='elbe add')
+    aparser.add_argument('xmlfile')
+    aparser.add_argument('pkg', nargs='+')
 
-    if len(args) < 2:
-        print('Wrong number of arguments')
-        oparser.print_help()
-        sys.exit(86)
+    args = aparser.parse_args(argv)
 
-    xmlfile = args[0]
-    pkg_lst = args[1:]
+    xmlfile = args.xmlfile
+    pkg_lst = args.pkg
 
     try:
         xml = ElbeXML(xmlfile)

-- 
2.45.2



More information about the elbe-devel mailing list