Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArgumentParser epilog and description formatting in conjunction with ArgumentDefaultsHelpFormatter

I'm using argparse to take in command line input and also to produce help text. I want to use ArgumentDefaultsHelpFormatter as the formatter_class, however this prevents me from also using RawDescriptionHelpFormatter which would allow me to add custom formatting to my description or epilog.

Is there a sensible method of achieving this aside from writing code to produce text for default values myself? According to the argparse docs, all internals of ArgumentParser are considered implementation details, not public API, so sub-classing isn't an attractive option.

like image 995
Spycho Avatar asked Aug 27 '13 10:08

Spycho


People also ask

What are Nargs?

nargs stands for Number Of Arguments.

How do you add an optional argument in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

What is Argparse ArgumentParser ()?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.


1 Answers

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.

like image 199
Spycho Avatar answered Sep 17 '22 19:09

Spycho