[elbe-devel] [PATCH 12/19] elbepack: get_archive: migrate to argparse

Thomas Weißschuh thomas.weissschuh at linutronix.de
Tue Jul 9 09:23:45 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/get_archive.py | 19 ++++++++-----------
 1 file changed, 8 insertions(+), 11 deletions(-)

diff --git a/elbepack/commands/get_archive.py b/elbepack/commands/get_archive.py
index e331d20dc4ba..25128b8508a7 100644
--- a/elbepack/commands/get_archive.py
+++ b/elbepack/commands/get_archive.py
@@ -2,10 +2,10 @@
 # SPDX-License-Identifier: GPL-3.0-or-later
 # SPDX-FileCopyrightText: 2013, 2017 Linutronix GmbH
 
+import argparse
 import os
 import sys
 from base64 import standard_b64decode
-from optparse import OptionParser
 
 from elbepack.treeutils import etree
 
@@ -18,28 +18,25 @@ def unbase(s, fname):
 
 def run_command(argv):
 
-    oparser = OptionParser(
-        usage='usage: %prog get_archive <xmlfile> <archive>')
-    (_, args) = oparser.parse_args(argv)
+    aparser = argparse.ArgumentParser(prog='elbe get_archive')
+    aparser.add_argument('xmlfile')
+    aparser.add_argument('archive')
 
-    if len(args) != 2:
-        print('Wrong number of arguments')
-        oparser.print_help()
-        sys.exit(101)
+    args = aparser.parse_args(argv)
 
-    if os.path.exists(args[1]):
+    if os.path.exists(args.archive):
         print('archive already exists, bailing out')
         sys.exit(102)
 
     try:
-        xml = etree(args[0])
+        xml = etree(args.xmlfile)
     except BaseException:
         print('Error reading xml file!')
         sys.exit(103)
 
     if xml.has('archive') and not xml.text('archive') is None:
         try:
-            unbase(xml.text('archive'), args[1])
+            unbase(xml.text('archive'), args.archive)
         except BaseException:
             print('Error writing archive')
             sys.exit(104)

-- 
2.45.2



More information about the elbe-devel mailing list