argparse_compat

Command-line parsing library

This module is an optparse-inspired command-line parsing library that:

  • handles both optional and positional arguments
  • produces highly informative usage messages
  • supports parsers that dispatch to sub-parsers

The following is a simple usage example that sums integers from the command-line and writes the result to a file:

parser = argparse.ArgumentParser(
    description='sum the integers at the command line')
parser.add_argument(
    'integers', metavar='int', nargs='+', type=int,
    help='an integer to be summed')
parser.add_argument(
    '--log', default=sys.stdout, type=argparse.FileType('w'),
    help='the file where the sum should be written')
args = parser.parse_args()
args.log.write('%s' % sum(args.integers))
args.log.close()

The module contains the following public classes:

  • ArgumentParser – The main entry point for command-line parsing. As the
    example above shows, the add_argument() method is used to populate the parser with actions for optional and positional arguments. Then the parse_args() method is invoked to convert the args at the command-line into an object with attributes.
  • ArgumentError – The exception raised by ArgumentParser objects when
    there are errors with the parser’s actions. Errors raised while parsing the command-line are caught by ArgumentParser and emitted as command-line messages.
  • FileType – A factory for defining types of files to be created. As the
    example above shows, instances of FileType are typically passed as the type= argument of add_argument() calls.
  • Action – The base class for parser actions. Typically actions are
    selected by passing strings like ‘store_true’ or ‘append_const’ to the action= argument of add_argument(). However, for greater customization of ArgumentParser actions, subclasses of Action may be defined and passed as the action= argument.
  • HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter,
    ArgumentDefaultsHelpFormatter – Formatter classes which may be passed as the formatter_class= argument to the ArgumentParser constructor. HelpFormatter is the default, RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser not to change the formatting for help text, and ArgumentDefaultsHelpFormatter adds information about argument defaults to the help.

All other classes in this module are considered implementation details. (Also note that HelpFormatter and RawDescriptionHelpFormatter are only considered public as object names – the API of the formatter objects is still considered an implementation detail.)

Module Contents

Classes

_AttributeHolder() Abstract base class that provides __repr__.
HelpFormatter(self,prog,indent_increment=2,max_help_position=24,width=None) Formatter for generating usage messages and argument help strings.
RawDescriptionHelpFormatter() Help message formatter which retains any formatting in descriptions.
RawTextHelpFormatter() Help message formatter which retains formatting of all help text.
ArgumentDefaultsHelpFormatter() Help message formatter which adds default values to argument help.
ArgumentError(self,argument,message) An error from creating or using an argument (optional or positional).
ArgumentTypeError() An error from trying to convert a command line string to a type.
Action(self,option_strings,dest,nargs=None,const=None,default=None,type=None,choices=None,required=False,help=None,metavar=None) Information about how to convert command line strings to Python objects.
_StoreAction(self,option_strings,dest,nargs=None,const=None,default=None,type=None,choices=None,required=False,help=None,metavar=None)
_StoreConstAction(self,option_strings,dest,const,default=None,required=False,help=None,metavar=None)
_StoreTrueAction(self,option_strings,dest,default=False,required=False,help=None)
_StoreFalseAction(self,option_strings,dest,default=True,required=False,help=None)
_AppendAction(self,option_strings,dest,nargs=None,const=None,default=None,type=None,choices=None,required=False,help=None,metavar=None)
_AppendConstAction(self,option_strings,dest,const,default=None,required=False,help=None,metavar=None)
_CountAction(self,option_strings,dest,default=None,required=False,help=None)
_HelpAction(self,option_strings,dest=SUPPRESS,default=SUPPRESS,help=None)
_VersionAction(self,option_strings,version=None,dest=SUPPRESS,default=SUPPRESS,help=”show program’s version number and exit”)
_SubParsersAction(self,option_strings,prog,parser_class,dest=SUPPRESS,help=None,metavar=None)
FileType(self,mode=”r”,bufsize=None) Factory for creating file object types
Namespace(self,**kwargs) Simple object for storing attributes.
_ActionsContainer(self,description,prefix_chars,argument_default,conflict_handler)
_ArgumentGroup(self,container,title=None,description=None,**kwargs)
_MutuallyExclusiveGroup(self,container,required=False)
ArgumentParser(self,prog=None,usage=None,description=None,epilog=None,version=None,parents=list,formatter_class=HelpFormatter,prefix_chars=”-“,fromfile_prefix_chars=None,argument_default=None,conflict_handler=”error”,add_help=True) Object for parsing command line strings into Python objects.

Functions

sorted(iterable,reverse=False)
_callable(obj)
_ensure_value(namespace,name,value)
_get_action_name(argument)
sorted(iterable, reverse=False)
_callable(obj)
class _AttributeHolder

Abstract base class that provides __repr__.

The __repr__ method returns a string in the format::
ClassName(attr=name, attr=name, …)

The attributes are determined either by a class-level attribute, ‘_kwarg_names’, or by inspecting the instance __dict__.

__repr__()
_get_kwargs()
_get_args()
_ensure_value(namespace, name, value)
class HelpFormatter(prog, indent_increment=2, max_help_position=24, width=None)

Formatter for generating usage messages and argument help strings.

Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.

__init__(prog, indent_increment=2, max_help_position=24, width=None)
_indent()
_dedent()
class _Section(formatter, parent, heading=None)
__init__(formatter, parent, heading=None)
format_help()
_add_item(func, args)
start_section(heading)
end_section()
add_text(text)
add_usage(usage, actions, groups, prefix=None)
add_argument(action)
add_arguments(actions)
format_help()
_join_parts(part_strings)
_format_usage(usage, actions, groups, prefix)
_format_actions_usage(actions, groups)
_format_text(text)
_format_action(action)
_format_action_invocation(action)
_metavar_formatter(action, default_metavar)
_format_args(action, default_metavar)
_expand_help(action)
_iter_indented_subactions(action)
_split_lines(text, width)
_fill_text(text, width, indent)
_get_help_string(action)
class RawDescriptionHelpFormatter

Help message formatter which retains any formatting in descriptions.

Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.

_fill_text(text, width, indent)
class RawTextHelpFormatter

Help message formatter which retains formatting of all help text.

Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.

_split_lines(text, width)
class ArgumentDefaultsHelpFormatter

Help message formatter which adds default values to argument help.

Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.

_get_help_string(action)
_get_action_name(argument)
class ArgumentError(argument, message)

An error from creating or using an argument (optional or positional).

The string value of this exception is the message, augmented with information about the argument that caused it.

__init__(argument, message)
__str__()
class ArgumentTypeError

An error from trying to convert a command line string to a type.

class Action(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)

Information about how to convert command line strings to Python objects.

Action objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line. The keyword arguments to the Action constructor are also all attributes of Action instances.

Keyword Arguments:

  • option_strings – A list of command-line option strings which

    should be associated with this action.

  • dest – The name of the attribute to hold the created object(s)

  • nargs – The number of command-line arguments that should be

    consumed. By default, one argument will be consumed and a single value will be produced. Other values include:

    • N (an integer) consumes N arguments (and produces a list)
    • ‘?’ consumes zero or one arguments
    • ‘*’ consumes zero or more arguments (and produces a list)
    • ‘+’ consumes one or more arguments (and produces a list)

    Note that the difference between the default and nargs=1 is that with the default, a single value will be produced, while with nargs=1, a list containing a single value will be produced.

  • const – The value to be produced if the option is specified and the

    option uses an action that takes no values.

  • default – The value to be produced if the option is not specified.

  • type – The type which the command-line arguments should be converted

    to, should be one of ‘string’, ‘int’, ‘float’, ‘complex’ or a callable object that accepts a single string argument. If None, ‘string’ is assumed.

  • choices – A container of values that should be allowed. If not None,

    after a command-line argument has been converted to the appropriate type, an exception will be raised if it is not a member of this collection.

  • required – True if the action must always be specified at the

    command line. This is only meaningful for optional command-line arguments.

  • help – The help string describing the argument.

  • metavar – The name to be used for the option’s argument with the

    help string. If None, the ‘dest’ value will be used as the name.

__init__(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
_get_kwargs()
__call__(parser, namespace, values, option_string=None)
class _StoreAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
__init__(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
__call__(parser, namespace, values, option_string=None)
class _StoreConstAction(option_strings, dest, const, default=None, required=False, help=None, metavar=None)
__init__(option_strings, dest, const, default=None, required=False, help=None, metavar=None)
__call__(parser, namespace, values, option_string=None)
class _StoreTrueAction(option_strings, dest, default=False, required=False, help=None)
__init__(option_strings, dest, default=False, required=False, help=None)
class _StoreFalseAction(option_strings, dest, default=True, required=False, help=None)
__init__(option_strings, dest, default=True, required=False, help=None)
class _AppendAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
__init__(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)
__call__(parser, namespace, values, option_string=None)
class _AppendConstAction(option_strings, dest, const, default=None, required=False, help=None, metavar=None)
__init__(option_strings, dest, const, default=None, required=False, help=None, metavar=None)
__call__(parser, namespace, values, option_string=None)
class _CountAction(option_strings, dest, default=None, required=False, help=None)
__init__(option_strings, dest, default=None, required=False, help=None)
__call__(parser, namespace, values, option_string=None)
class _HelpAction(option_strings, dest=SUPPRESS, default=SUPPRESS, help=None)
__init__(option_strings, dest=SUPPRESS, default=SUPPRESS, help=None)
__call__(parser, namespace, values, option_string=None)
class _VersionAction(option_strings, version=None, dest=SUPPRESS, default=SUPPRESS, help="show program's version number and exit")
__init__(option_strings, version=None, dest=SUPPRESS, default=SUPPRESS, help="show program's version number and exit")
__call__(parser, namespace, values, option_string=None)
class _SubParsersAction(option_strings, prog, parser_class, dest=SUPPRESS, help=None, metavar=None)
class _ChoicesPseudoAction(name, help)
__init__(name, help)
__init__(option_strings, prog, parser_class, dest=SUPPRESS, help=None, metavar=None)
add_parser(name, **kwargs)
_get_subactions()
__call__(parser, namespace, values, option_string=None)
class FileType(mode="r", bufsize=None)

Factory for creating file object types

Instances of FileType are typically passed as type= arguments to the ArgumentParser add_argument() method.

Keyword Arguments:
  • mode – A string indicating how the file is to be opened. Accepts the
    same values as the builtin open() function.
  • bufsize – The file’s desired buffer size. Accepts the same values as
    the builtin open() function.
__init__(mode="r", bufsize=None)
__call__(string)
__repr__()
class Namespace(**kwargs)

Simple object for storing attributes.

Implements equality by attribute names and values, and provides a simple string representation.

__init__(**kwargs)
__eq__(other)
__ne__(other)
__contains__(key)
class _ActionsContainer(description, prefix_chars, argument_default, conflict_handler)
__init__(description, prefix_chars, argument_default, conflict_handler)
register(registry_name, value, object)
_registry_get(registry_name, value, default=None)
set_defaults(**kwargs)
get_default(dest)
add_argument(*args, **kwargs)

add_argument(dest, …, name=value, …) add_argument(option_string, option_string, …, name=value, …)

add_argument_group(*args, **kwargs)
add_mutually_exclusive_group(**kwargs)
_add_action(action)
_remove_action(action)
_add_container_actions(container)
_get_positional_kwargs(dest, **kwargs)
_get_optional_kwargs(*args, **kwargs)
_pop_action_class(kwargs, default=None)
_get_handler()
_check_conflict(action)
_handle_conflict_error(action, conflicting_actions)
_handle_conflict_resolve(action, conflicting_actions)
class _ArgumentGroup(container, title=None, description=None, **kwargs)
__init__(container, title=None, description=None, **kwargs)
_add_action(action)
_remove_action(action)
class _MutuallyExclusiveGroup(container, required=False)
__init__(container, required=False)
_add_action(action)
_remove_action(action)
class ArgumentParser(prog=None, usage=None, description=None, epilog=None, version=None, parents=list, formatter_class=HelpFormatter, prefix_chars="-", fromfile_prefix_chars=None, argument_default=None, conflict_handler="error", add_help=True)

Object for parsing command line strings into Python objects.

Keyword Arguments:
  • prog – The name of the program (default: sys.argv[0])
  • usage – A usage message (default: auto-generated from arguments)
  • description – A description of what the program does
  • epilog – Text following the argument descriptions
  • parents – Parsers whose arguments should be copied into this one
  • formatter_class – HelpFormatter class for printing help messages
  • prefix_chars – Characters that prefix optional arguments
  • fromfile_prefix_chars – Characters that prefix files containing
    additional arguments
  • argument_default – The default value for all arguments
  • conflict_handler – String indicating how to handle conflicts
  • add_help – Add a -h/-help option
__init__(prog=None, usage=None, description=None, epilog=None, version=None, parents=list, formatter_class=HelpFormatter, prefix_chars="-", fromfile_prefix_chars=None, argument_default=None, conflict_handler="error", add_help=True)
_get_kwargs()
add_subparsers(**kwargs)
_add_action(action)
_get_optional_actions()
_get_positional_actions()
parse_args(args=None, namespace=None)
parse_known_args(args=None, namespace=None)
_parse_known_args(arg_strings, namespace)
_read_args_from_files(arg_strings)
convert_arg_line_to_args(arg_line)
_match_argument(action, arg_strings_pattern)
_match_arguments_partial(actions, arg_strings_pattern)
_parse_optional(arg_string)
_get_option_tuples(option_string)
_get_nargs_pattern(action)
_get_values(action, arg_strings)
_get_value(action, arg_string)
_check_value(action, value)
format_usage()
format_help()
format_version()
_get_formatter()
print_usage(file=None)
print_help(file=None)
print_version(file=None)
_print_message(message, file=None)
exit(status=0, message=None)
error(message)

error(message: string)

Prints a usage message incorporating the message to stderr and exits.

If you override this in a subclass, it should not return – it should either exit or raise an exception.