From 7103a296baf4b20d2a70106f36d97cf3bf3663f9 Mon Sep 17 00:00:00 2001 From: Mylloon Date: Wed, 17 Apr 2024 15:45:37 +0200 Subject: [PATCH] Add proper argument parser --- converter.py | 29 ++++++++++++++++++----------- 1 file changed, 18 insertions(+), 11 deletions(-) diff --git a/converter.py b/converter.py index 258d52e..122c57a 100644 --- a/converter.py +++ b/converter.py @@ -1,7 +1,6 @@ +from argparse import ArgumentParser from csv import reader as csv_reader from pprint import pformat -from pprint import pp as pprint -from sys import argv, stderr from xml.dom.minidom import parseString as xml_parser from xml.etree import ElementTree @@ -38,7 +37,6 @@ class System: represented as a couple (member, interpretation) """ - # TODO: Est-ce que on garde ça ?? # Interpretation of extra symbols added if necessary extra_symbols = ["[", "]"] for _, substitution in substitutions: @@ -107,18 +105,27 @@ def lsystems_xml(systems: list[System]) -> ElementTree.Element: if __name__ == "__main__": - if len(argv) != 2: - pprint(f"Syntax error:\n\tpython {argv[0]} file.csv", stream=stderr) - exit(1) - # TODO: Check if we have to dump to stdout or we write into a file - # use `argparse` for cli arguments + parser = ArgumentParser(description="Generate XML representation of L-systems") + parser.add_argument( + "file", metavar="FILE", help="CSV file containing L-system data" + ) + parser.add_argument( + "-o", "--output", metavar="OUTPUT_FILE", help="Specify output file for XML" + ) + + args = parser.parse_args() # Read data - lsystems = data_reader(argv[1]) + lsystems = data_reader(args.file) # Generate XML xml = lsystems_xml(lsystems) - # Print XML + # Output XML dom = xml_parser(ElementTree.tostring(xml)) - print(dom.toprettyxml(encoding="UTF-8").decode()) + pretty_xml = dom.toprettyxml(encoding="UTF-8").decode() + if args.output: + with open(args.output, "w") as output_file: + output_file.write(pretty_xml) + else: + print(pretty_xml)