[elbe-devel] [PATCH 06/19] elbepack: validate: migrate to argparse

Thomas Weißschuh thomas.weissschuh at linutronix.de
Tue Jul 9 09:23:39 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/validate.py | 29 +++++++++++++----------------
 1 file changed, 13 insertions(+), 16 deletions(-)

diff --git a/elbepack/commands/validate.py b/elbepack/commands/validate.py
index 00feeb6bcb0a..d4e9a628f55a 100644
--- a/elbepack/commands/validate.py
+++ b/elbepack/commands/validate.py
@@ -2,41 +2,38 @@
 # SPDX-License-Identifier: GPL-3.0-or-later
 # SPDX-FileCopyrightText: 2013-2017 Linutronix GmbH
 
+import argparse
 import os
 import sys
-from optparse import OptionParser
 
 from elbepack.elbexml import ElbeXML, ValidationError, ValidationMode
 from elbepack.validate import validate_xml
 
 
 def run_command(argv):
-    oparser = OptionParser(usage='usage: %prog validate <xmlfile>')
-    oparser.add_option('--validate-urls', dest='validate_urls',
-                       help='try to access specified repositories',
-                       default=False, action='store_true')
+    aparser = argparse.ArgumentParser(prog='elbe validate')
+    aparser.add_argument('--validate-urls', dest='validate_urls',
+                         help='try to access specified repositories',
+                         default=False, action='store_true')
+    aparser.add_argument('xmlfile')
 
-    (opt, args) = oparser.parse_args(argv)
+    args = aparser.parse_args(argv)
 
-    if not args:
-        oparser.print_help()
-        sys.exit(58)
-
-    if not os.path.exists(args[0]):
-        print(f'{args[0]} - file not found')
-        oparser.print_help()
+    if not os.path.exists(args.xmlfile):
+        print(f'{args.xmlfile} - file not found')
+        aparser.print_help()
         sys.exit(59)
 
-    validation = validate_xml(args[0])
+    validation = validate_xml(args.xmlfile)
     if validation:
         print('validation failed')
         for i in validation:
             print(i)
         sys.exit(60)
 
-    if opt.validate_urls:
+    if args.validate_urls:
         try:
-            ElbeXML(args[0], url_validation=ValidationMode.CHECK_ALL)
+            ElbeXML(args.xmlfile, url_validation=ValidationMode.CHECK_ALL)
         except ValidationError as e:
             print(e)
             sys.exit(61)

-- 
2.45.2



More information about the elbe-devel mailing list