Creating an –all argument

Question:

I am creating a python script that parses log files in XML-format into a SQLite database file. There are several different types of log files, and by default the script only processes the process-*.xml files in the given folder. Using argparser options the user can control which log files should be included.

argparser = argparse.ArgumentParser(description="Process log files into a SQLite database.")
argparser.add_argument("--control", action=argparse.BooleanOptionalAction, default=False, help="parse control-*.xml into the database")
argparser.add_argument("--dream", action=argparse.BooleanOptionalAction, default=False, help="parse dream-*.xml into the database")
argparser.add_argument("--error", action=argparse.BooleanOptionalAction, default=False, help="parse error-*.xml into the database")
argparser.add_argument("--lis", action=argparse.BooleanOptionalAction, default=False, help="parse lis-*.xml into the database")
argparser.add_argument("--pass", action=argparse.BooleanOptionalAction, default=False, help="parse pass-*.xml into the database", dest="pass_xml")  # The default .pass not valid attribute
argparser.add_argument("--process", action=argparse.BooleanOptionalAction, default=True, help="parse process-*.xml into the database")
argparser.add_argument("--uif", action=argparse.BooleanOptionalAction, default=False, help="parse uif-*.xml into the database")

There are also some additional parameters not concerning this that I didn’t include here for readability.

I would like to add an --all argument that sets all of the above arguments to True. Even better would be if e.g. --all --no-control would set all arguments to True except control that would be left as False. How can this be acomplished?

Asked By: LapplandsCohan

||

Answers:

What about the simple and obvious solution?

argparser.add_argument("--all", action=argparse.store_true, default=False, help="All of the above")

...

if args.all:
    args.control = True
    args.dream = True
    args.error = True
    ...

Addition:

To get --all --no-foo to work remove default=False from the .add_arguments, which then would set the value to None if not specified and False if --no-foo if specified. Then use

if args.all:
    if args.foo == None: args.foo = True
    if args.bar == None: args.bar = True
    ...

This way the arguments will be set to True only if not explicitly set to False using the --no-foo option.

Answered By: tripleee
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.