changeset 70:f887d8a68e5e

Cleanups, move argparser initialization into a function.
author Matti Hamalainen <ccr@tnsp.org>
date Thu, 09 Dec 2021 08:59:41 +0200
parents 7a77c78ff5b8
children 8481f8f52a84
files lxmldump.py
diffstat 1 files changed, 106 insertions(+), 103 deletions(-) [+]
line wrap: on
line diff
--- a/lxmldump.py	Mon Oct 18 00:38:37 2021 +0300
+++ b/lxmldump.py	Thu Dec 09 08:59:41 2021 +0200
@@ -463,119 +463,122 @@
             indent=pkk_geti(indent)))
 
 
+def pkk_get_argparser():
+    optparser = argparse.ArgumentParser(
+        usage="%(prog)s [options] <input xml file(s)>",
+        add_help=False
+        )
+
+    optparser.add_argument("filenames",
+        type=str, action="extend", nargs="*",
+        metavar="filename",
+        help="XML filename(s)")
+
+    optparser.add_argument("-h", "--help",
+        dest="show_help",
+        action="store_true",
+        help="show this help message")
+
+    optparser.add_argument("-m", "--mode",
+        dest="mode",
+        action=pkk_set_mode,
+        default=PKK_MODE_NORMAL,
+        help="set output mode (see below)")
+
+    optparser.add_argument("-s", "--set",
+        action=pkk_set_value,
+        metavar="ID=STR",
+        help='set format string (see below)')
+
+    optparser.add_argument("-n", "--normalize",
+        dest="normalize",
+        action="store_true",
+        help="output NFC normalized Unicode")
+
+    optparser.add_argument("-a", "--annotate",
+        dest="annotate",
+        action="store_true",
+        help="annotate strings")
+
+    optparser.add_argument("-i", "--indent",
+        dest="indent",
+        type=functools.partial(pkk_arg_range, vmin=0, vmax=32), default=4,
+        metavar="N",
+        help='set indentation width (default: %(default)s)')
+
+    optparser.add_argument("-p", "--debug",
+        dest="debug",
+        action="store_true",
+        help=argparse.SUPPRESS)
+
+    return optparser
+
+
 ###
 ### Main program starts
 ###
-signal.signal(signal.SIGINT, pkk_signal_handler)
-
-optparser = argparse.ArgumentParser(
-    usage="%(prog)s [options] <input xml file(s)>",
-    add_help=False
-    )
-
-optparser.add_argument("filenames",
-    type=str, action="extend", nargs="*",
-    metavar="filename",
-    help="XML filename(s)")
-
-optparser.add_argument("-h", "--help",
-    dest="show_help",
-    action="store_true",
-    help="show this help message")
-
-optparser.add_argument("-m", "--mode",
-    dest="mode",
-    action=pkk_set_mode,
-    default=PKK_MODE_NORMAL,
-    help="set output mode (see below)")
+if __name__ == "__main__":
+    signal.signal(signal.SIGINT, pkk_signal_handler)
 
-optparser.add_argument("-s", "--set",
-    action=pkk_set_value,
-    metavar="ID=STR",
-    help='set format string (see below)')
-
-optparser.add_argument("-n", "--normalize",
-    dest="normalize",
-    action="store_true",
-    help="output NFC normalized Unicode")
-
-optparser.add_argument("-a", "--annotate",
-    dest="annotate",
-    action="store_true",
-    help="annotate strings")
-
-optparser.add_argument("-i", "--indent",
-    dest="indent",
-    type=functools.partial(pkk_arg_range, vmin=0, vmax=32), default=4,
-    metavar="N",
-    help='set indentation width (default: %(default)s)')
-
-optparser.add_argument("-p", "--debug",
-    dest="debug",
-    action="store_true",
-    help=argparse.SUPPRESS)
+    ### Parse arguments
+    optparser = pkk_get_argparser()
+    pkk_cfg = optparser.parse_args()
 
 
-### Parse arguments
-pkk_cfg = optparser.parse_args()
+    ### Show help if needed
+    if len(pkk_cfg.filenames) == 0 or pkk_cfg.show_help:
+        print("lxmldump - Convert and dump ISO/FDIS 1951 XML file data\n"
+        "Programmed and designed by Matti 'ccr' Hämäläinen <ccr@tnsp.org>\n"
+        "(C) Copyright 2021 Tecnic Software productions (TNSP)\n")
+        optparser.print_help()
+        print(u"\nAvailable output modes:")
+        print("  " + ", ".join(pkk_modes_list.values()))
+
+        if pkk_cfg.mode not in [PKK_MODE_NORMAL, PKK_MODE_ANKI]:
+            pkk_cfg.mode = PKK_MODE_NORMAL
+
+        print(u"\nAvailable format strings and values (mode '{}'):".format(
+            pkk_modes_list[pkk_cfg.mode]))
+
+        for mid in pkk_mode_defaults:
+            stmp = pkk_get_value(mid).replace("\\", "\\\\").replace("\n", "\\n")
+            print(u"  {:22s} : '{}'".format(mid, stmp))
+
+        sys.exit(0)
 
 
-### Show help if needed
-if len(pkk_cfg.filenames) == 0 or pkk_cfg.show_help:
-    print("lxmldump - Convert and dump ISO/FDIS 1951 XML file data\n"
-    "Programmed and designed by Matti 'ccr' Hämäläinen <ccr@tnsp.org>\n"
-    "(C) Copyright 2021 Tecnic Software productions (TNSP)\n")
-    optparser.print_help()
-    print(u"\nAvailable output modes:")
-    print("  " + ", ".join(pkk_modes_list.values()))
-
-    if pkk_cfg.mode not in [PKK_MODE_NORMAL, PKK_MODE_ANKI]:
-        pkk_cfg.mode = PKK_MODE_NORMAL
-
-    print(u"\nAvailable format strings and values (mode '{}'):".format(
-        pkk_modes_list[pkk_cfg.mode]))
+    ### Handle each input file
+    for filename in pkk_cfg.filenames:
+        # Parse XML file into element tree
+        try:
+            uxml = xmlET.parse(filename)
+        except Exception as e:
+            pkk_fatal(u"SVG/XML parsing failed: {0}".format(str(e)))
 
-    for mid in pkk_mode_defaults:
-        stmp = pkk_get_value(mid).replace("\\", "\\\\").replace("\n", "\\n")
-        print(u"  {:22s} : '{}'".format(mid, stmp))
-
-    sys.exit(0)
-
+        # Dump output
+        try:
+            xroot = uxml.getroot()
+            for dnode in xroot.findall("./DictionaryEntry"):
 
-### Handle each input file
-for filename in pkk_cfg.filenames:
-    # Parse XML file into element tree
-    try:
-        uxml = xmlET.parse(filename)
-    except Exception as e:
-        pkk_fatal(u"SVG/XML parsing failed: {0}".format(str(e)))
+                if pkk_cfg.debug and dnode.attrib["identifier"] not in pkk_debug_list:
+                    continue
 
-    # Dump output
-    try:
-        xroot = uxml.getroot()
-        for dnode in xroot.findall("./DictionaryEntry"):
-
-            if pkk_cfg.debug and dnode.attrib["identifier"] not in pkk_debug_list:
-                continue
-
-            if pkk_cfg.mode in [PKK_MODE_NORMAL, PKK_MODE_ANKI]:
-                try:
-                    pkk_output_node(0, dnode)
-                except Exception as e:
-                    print("")
+                if pkk_cfg.mode in [PKK_MODE_NORMAL, PKK_MODE_ANKI]:
+                    try:
+                        pkk_output_node(0, dnode)
+                    except Exception as e:
+                        print("")
+                        pkk_dump_recursive(0, dnode)
+                        print(str(e))
+                        sys.exit(0)
+                elif pkk_cfg.mode == PKK_MODE_DUMP:
                     pkk_dump_recursive(0, dnode)
-                    print(str(e))
-                    sys.exit(0)
-            elif pkk_cfg.mode == PKK_MODE_DUMP:
-                pkk_dump_recursive(0, dnode)
-                print("")
-            elif pkk_cfg.mode == PKK_MODE_XML:
-                pkk_print(xmlET.tostring(dnode, encoding="utf8").decode("utf8") + "\n\n")
-            else:
-                pkk_fatal("Invalid operation mode?")
+                    print("")
+                elif pkk_cfg.mode == PKK_MODE_XML:
+                    pkk_print(xmlET.tostring(dnode, encoding="utf8").decode("utf8") + "\n\n")
+                else:
+                    pkk_fatal("Invalid operation mode?")
 
-    except (BrokenPipeError, IOError) as e:
-        sys.stderr.close()
-        sys.exit(1)
-
-sys.exit(0)
+        except (BrokenPipeError, IOError) as e:
+            sys.stderr.close()
+            sys.exit(1)