ArgumentParser, parsing for arguments

The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

ArgumentParser objects

https://docs.python.org/3.7/library/argparse.html#argumentparser-objects

Create a new ArgumentParser object. All parameters should be passed as keyword arguments. Each parameter has its own more detailed description below, but in short they are:

• prog — The name of the program (default: sys.argv[0])
• usage — the string describing the program usage (default: generated from arguments added to parser)
• description — Text to display before the argument help (default: none)
• epilog — Text to display after the argument help (default: none)
• parents — A list of ArgumentParser objects whose arguments should also be included
• formatter_class — A class for customizing the help output
• prefix_chars — The set of characters the prefix optional arguments (default: ‘-‘)
• fromfile_prefix_chars — The set of characters that prefix files from which additional arguments should be read (default: None)
• argument_default — The global default value for arguments (default: None)
• conflict_handler — The strategy for resolving conflicting options (usually unnecessary)
• add_help — Add a -h/—help option to the parser (default: True)
• allow_abbrev — Allow long options to be abbreviated if the abbreviation is unambiguous. (default: True)

The following sections describe how each of these are used.

-> prog <-

https://docs.python.org/3.7/library/argparse.html#prog

By default, ArgumentParser objects use sys.argv[0] to determine how to display the name of the program in help messages. This default is almost always desirable because it will make the help messages match how the program was invoked on the command line.

Note that the program name, whether determined from sys.argv[0] or from the prog= argument, is available to help messages using the %(prog)s format specifier.

-> usage <-

https://docs.python.org/3.7/library/argparse.html#usage

By default, ArgumentParser calculates the usage message from the arguments it contains.

The default message can be overridden with the usage= keyword argument.
The %(prog)s format specifier is available to fill in the program name in your usage messages.

-> description <-

https://docs.python.org/3.7/library/argparse.html#description

Most calls to the ArgumentParser constructor will use the description= keyword argument. This argument give a brief description of what the program does and how it works. In help messages, the description is display between the command-line usage string and the help messages for the various arguments.

By default, the description will be line-wrapped so that it fits within the given space. To change this behavior, see the formatter_class argument.

-> epilog <-

https://docs.python.org/3.7/library/argparse.html#epilog

Some programs like to display additional description of the program after the description of the arguments. Such text can be specified using the epilog= argument to ArgumentParser.

As with the description argument, the epilog= text is by default line-wrapped, but this behavior can be adjusted with the formatter_class argument to ArgumentParser.

-> parents <-

https://docs.python.org/3.7/library/argparse.html#parents

Sometimes, several parsers share a common set of arguments. Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to parents= argument to ArgumentParser can be used. The parents= argument takes a list of ArgumentParser objects, collects all the positional and optional actions from them, and adds these actions to ArgumentParser object being constructed.

Note that most parent parsers will specify add_help=False. Otherwise, the ArgumentParser will see two -h/—help options (one in the parent and one in the child) and raise an error.

NOTE: You must fully initialize the parsers before passing them via parents=. If you change the parents after the child parser, those changes will not reflected in the child.

-> formatter_class <-

https://docs.python.org/3.7/library/argparse.html#formatter-class

ArgumentParser objects allow the help formatting to be customized by specifying an alternate formatting class. Currently, there are four such classes:
class argparse.RawDescriptionHelpFormatter
class argparse.RawTextHelpFormatter
class argparse.ArgumentDefaultsHelpFormatter
class argparse.MetavarTypeHelpFormatter

RawDescriptionHelpFormatter and RawTextHelpFormatter give more control over how textual descriptions are displayed. By default, ArgumentParser objects line-wrap the description and epilog texts in command-line help messages.

Passing RawDescriptionHelpFormatter as formatter_class= indicates that description and epilog are already correctly formatted and should not line-wrapped.

RawTextHelpFormatter maintains whitespace for all sorts of help text, including argument descriptions. However, multiple new lines are replaced with one. If you wish to preserve multiple blank lines, add spaces between the newlines.

ArgumentDefaultsHelpFormatter automatically adds information about default values to each of the argument help messages.

MetavarTypeHelpFormatter uses the name of the type argument for each arguments as the replay name for its values (rather than using the dest as the regular formatter does).

-> prefix_chars <-

https://docs.python.org/3.7/library/argparse.html#prefix-chars

Most command-line options will use - as the prefix, e.g. -f/—foo. Parsers that need to support different or additional prefix characters, e.g. for options like +f or /foo, may specify them using the prefix_chars= argument to the ArgumentParser constructor.

The prefix_chars= argument defaults to -. Supplying a set of characters that does not include - will cause -f/—foo options to be disallowed.

-> from file_prefix_char <-

https://docs.python.org/3.7/library/argparse.html#fromfile-prefix-chars

Sometimes, for example when dealing with a particularly long argument lists, it may make sense to keep the list of arguments in a file rather than typing it out at the command line. If the fromfile_prefix_chars= argument is given to the ArgumentParser constructor, then arguments that start with any of the specified characters will be treated as files, and will be replaced by the arguments they contain.

Arguments read from a file must by default be one per line (but see also convert_arg_line_to_args()) and are treated as if they were in the same place as the original file referencing argument on the command line. So in the example above, the expression [‘-f’, ‘foo’, ‘@args.txt’] is considered equivalent to the expression [‘-f’, ‘foo’, ‘-f’, ’bar’].

The from file_prefix_chars= argument defaults to None, meaning that arguments will never be treated as file references.

-> argument_default <-

https://docs.python.org/3.7/library/argparse.html#argument-default

Generally, argument defaults are specified either by passing a default to add_argument() or by calling the set_defaults() methods with a specific set of name-values pairs. Sometimes however, it may be useful to specify a single parser-wide default for arguments. This can be accomplished by passing the argument_default= keyword argument to ArgumentParser. For example, to globally suppress attribute create on parse_args() calls, we supply argument_default=SUPPRESS.

-> allow_abbrev <-

https://docs.python.org/3.7/library/argparse.html#allow-abbrev

Normally, when you pass an argument list to the parse_args() method of an ArgumentParser, it recognizes abbreviations of long options.

This feature can be disabled by setting allow_abbrev to False.

-> conflict_handler <-

https://docs.python.org/3.7/library/argparse.html#conflict-handler

ArgumentParser objects do not allow two actions with the same option string. By default, ArgumentParser objects raise an exception if an attempt is made to create an argument with an option string that is already in use.

Sometimes (e.g. when using parents) it may be useful to simply override any older arguments with the same option string. To get this behavior, the value 'resolve’ can be supplied to the conflict_handler= argument of ArgumentParser.

Note that ArgumentParser objects only remove an action if all of its option strings are override. So, in the example above, the old -f/—foo action is retained as the -f action, because only the —foo option string was overridden.

-> add_help <-

https://docs.python.org/3.7/library/argparse.html#add-help

By default, ArgumentParser objects add an option which simple displays the parser’s help message. If -h or —help is supplied at the command line, the ArgumentParser help will be printed.
Occasionally, it may be useful to disable the addition of this help option. This can be achieved by passing False as the add_help= argument to ArgumentParser.
The help option is typically -h/—help. The exception to this is if the prefix_chars= is specified and does not include -, in which case -h and —help are not valid options. In this case, the first character in prefix_chars is used to prefix the help options.

Reference

https://docs.python.org/3.7/library/argparse.html

0%