Using Argparse and Json together

The args Namespace from parse_args can be transformed into a dictionary with: argparse_dict = vars(args) The JSON values are also in a dictionary, say json_dict. You can copy selected values from one dictionary to the other, or do a whole scale update: argparse_dict.update(json_dict) This way the json_dict values over write the argparse ones. If you … Read more

How to pass and parse a list of strings from command line with argparse.ArgumentParser in Python?

You need to define –names-list to take an arbitrary number of arguments. parser.add_argument(‘-n’, ‘–names-list’, nargs=”+”, default=[]) Note that options with arbitrary number of arguments don’t typically play well with positional arguments, though: # Is this 4 arguments to -n, or # 3 arguments and a single positional argument, or … myprog.py -n a b c … Read more

Python argparse dict arg

Here’s another solution using a custom action, if you want to specify dict key pairs together comma-separated — import argparse import sys parser = argparse.ArgumentParser(description=’parse key pairs into a dictionary’) class StoreDictKeyPair(argparse.Action): def __call__(self, parser, namespace, values, option_string=None): my_dict = {} for kv in values.split(“,”): k,v = kv.split(“=”) my_dict[k] = v setattr(namespace, self.dest, my_dict) parser.add_argument(“–key_pairs”, … Read more

argparse add example usage

You need to use the epilog and the formatter_class arguments to ArgumentParser if you want to have the help the example printed at the end (epilog) and to preserve the whitespace/formatting (formatter_class set to RawDescriptionHelpFormatter). Example by modifying your example above: import argparse example_text=””‘example: python test.py -t template/test.py python test.py -t template/test -c conf/test.conf python … Read more

argparse subparser monolithic help output

This is a bit tricky, as argparse does not expose a list of defined sub-parsers directly. But it can be done: import argparse # create the top-level parser parser = argparse.ArgumentParser(prog=’PROG’) parser.add_argument(‘–foo’, action=’store_true’, help=’foo help’) subparsers = parser.add_subparsers(help=’sub-command help’) # create the parser for the “a” command parser_a = subparsers.add_parser(‘a’, help=’a help’) parser_a.add_argument(‘bar’, type=int, help=’bar … Read more

ArgumentParser epilog and description formatting in conjunction with ArgumentDefaultsHelpFormatter

I just tried a multiple inheritance approach, and it works: class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter, argparse.RawDescriptionHelpFormatter): pass parser = argparse.ArgumentParser(description=’test\ntest\ntest.’, epilog=’test\ntest\ntest.’, formatter_class=CustomFormatter) This may break if the internals of these classes change though.