API Reference

Argh

class argh.ArghNamespace(*args, **kwargs)

A namespace object which collects the stack of functions.

class argh.ArghParser(*args, **kwargs)

A subclass of argparse.ArgumentParser with support for and a couple of convenience methods.

All methods are but wrappers for stand-alone functions add_commands(), autocomplete() and dispatch().

Uses PARSER_FORMATTER.

add_commands(*args, **kwargs)

Wrapper for add_commands().

autocomplete()

Wrapper for autocomplete().

dispatch(*args, **kwargs)

Wrapper for dispatch().

parse_args(args=None, namespace=None)

Wrapper for argparse.ArgumentParser.parse_args(). If namespace is not defined, argh.dispatching.ArghNamespace is used. This is required for functions to be properly used as commands.

set_default_command(*args, **kwargs)

Wrapper for set_default_command().

exception argh.AssemblingError

Raised if the parser could not be configured due to malformed or conflicting command declarations.

exception argh.CommandError(*args, code=None)

Intended to be raised from within a command. The dispatcher wraps this exception by default and prints its message without traceback, then exits with exit code 1.

Useful for print-and-exit tasks when you expect a failure and don’t want to startle the ordinary user by the cryptic output.

Consider the following example:

def foo(args):
    try:
        ...
    except KeyError as e:
        print(u'Could not fetch item: {0}'.format(e))
        sys.exit(1)

It is exactly the same as:

def bar(args):
    try:
        ...
    except KeyError as e:
        raise CommandError(u'Could not fetch item: {0}'.format(e))

To customize the exit status, pass an integer (as per sys.exit()) to the code keyword arg.

This exception can be safely used in both print-style and yield-style commands (see Tutorial).

exception argh.DispatchingError

Raised if the dispatching could not be completed due to misconfiguration which could not be determined on an earlier stage.

class argh.EntryPoint(name=None, parser_kwargs=None)

An object to which functions can be attached and then dispatched.

When called with an argument, the argument (a function) is registered at this entry point as a command.

When called without an argument, dispatching is triggered with all previously registered commands.

Usage:

from argh import EntryPoint

app = EntryPoint('main', dict(description='This is a cool app'))

@app
def ls():
    for i in range(10):
        print i

@app
def greet():
    print 'hello'

if __name__ == '__main__':
    app()
argh.PARSER_FORMATTER

alias of CustomFormatter

argh.add_commands(parser, functions, namespace=None, namespace_kwargs=None, func_kwargs=None, title=None, description=None, help=None)

Adds given functions as commands to given parser.

Parameters:
  • parser – an argparse.ArgumentParser instance.

  • functions – a list of functions. A subparser is created for each of them. If the function is decorated with arg(), the arguments are passed to argparse.ArgumentParser.add_argument(). See also dispatch() for requirements concerning function signatures. The command name is inferred from the function name. Note that the underscores in the name are replaced with hyphens, i.e. function name “foo_bar” becomes command name “foo-bar”.

  • namespace – an optional string representing the group of commands. For example, if a command named “hello” is added without the namespace, it will be available as “prog.py hello”; if the namespace if specified as “greet”, then the command will be accessible as “prog.py greet hello”. The namespace itself is not callable, so “prog.py greet” will fail and only display a help message.

  • func_kwargs – a dict of keyword arguments to be passed to each nested ArgumentParser instance created per command (i.e. per function). Members of this dictionary have the highest priority, so a function’s docstring is overridden by a help in func_kwargs (if present).

  • namespace_kwargs – a dict of keyword arguments to be passed to the nested ArgumentParser instance under given namespace.

Deprecated params that should be moved into namespace_kwargs:

Parameters:
  • title

    Deprecated since version 0.26.0: This argument will be removed in Argh v.0.30. Please use namespace_kwargs instead.

  • description

    Deprecated since version 0.26.0: This argument will be removed in Argh v.0.30. Please use namespace_kwargs instead.

  • help

    Deprecated since version 0.26.0: This argument will be removed in Argh v.0.30. Please use namespace_kwargs instead.

Note

This function modifies the parser object. Generally side effects are bad practice but we don’t seem to have any choice as ArgumentParser is pretty opaque. You may prefer add_commands() for a bit more predictable API.

Note

An attempt to add commands to a parser which already has a default function (e.g. added with set_default_command()) results in AssemblingError.

argh.add_subcommands(parser, namespace, functions, **namespace_kwargs)

A wrapper for add_commands().

These examples are equivalent:

add_commands(parser, [get, put], namespace='db',
             namespace_kwargs={
                 'title': 'database commands',
                 'help': 'CRUD for our silly database'
             })

add_subcommands(parser, 'db', [get, put],
                title='database commands',
                help='CRUD for our silly database')
argh.aliases(*names)

Defines alternative command name(s) for given function (along with its original name). Usage:

@aliases('co', 'check')
def checkout(args):
    ...

The resulting command will be available as checkout, check and co.

New in version 0.19.

argh.arg(*args, **kwargs)

Declares an argument for given function. Does not register the function anywhere, nor does it modify the function in any way.

The signature of the decorator matches that of argparse.ArgumentParser.add_argument(), only some keywords are not required if they can be easily guessed (e.g. you don’t have to specify type or action when an int or bool default value is supplied).

Typical use cases:

  • In combination with expects_obj() (which is not recommended);

  • in combination with ordinary function signatures to add details that cannot be expressed with that syntax (e.g. help message).

Usage:

from argh import arg

@arg('path', help='path to the file to load')
@arg('--format', choices=['yaml','json'])
@arg('-v', '--verbosity', choices=range(0,3), default=2)
def load(path, something=None, format='json', dry_run=False, verbosity=1):
    loaders = {'json': json.load, 'yaml': yaml.load}
    loader = loaders[args.format]
    data = loader(args.path)
    if not args.dry_run:
        if verbosity < 1:
            print('saving to the database')
        put_to_database(data)

In this example:

  • path declaration is extended with help;

  • format declaration is extended with choices;

  • dry_run declaration is not duplicated;

  • verbosity is extended with choices and the default value is overridden. (If both function signature and @arg define a default value for an argument, @arg wins.)

Note

It is recommended to avoid using this decorator unless there’s no way to tune the argument’s behaviour or presentation using ordinary function signatures. Readability counts, don’t repeat yourself.

argh.confirm(action, default=None, skip=False)

A shortcut for typical confirmation prompt.

Parameters:
  • action – a string describing the action, e.g. “Apply changes”. A question mark will be appended.

  • defaultbool or None. Determines what happens when user hits Enter without typing in a choice. If True, default choice is “yes”. If False, it is “no”. If None the prompt keeps reappearing until user types in a choice (not necessarily acceptable) or until the number of iteration reaches the limit. Default is None.

  • skipbool; if True, no interactive prompt is used and default choice is returned (useful for batch mode). Default is False.

Usage:

def delete(key, silent=False):
    item = db.get(Item, args.key)
    if confirm('Delete '+item.title, default=True, skip=silent):
        item.delete()
        print('Item deleted.')
    else:
        print('Operation cancelled.')

Returns None on KeyboardInterrupt event.

argh.dispatch(parser, argv=None, add_help_command=True, completion=True, pre_call=None, output_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, errors_file=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>, raw_output=False, namespace=None, skip_unknown_args=False)

Parses given list of arguments using given parser, calls the relevant function and prints the result.

The target function should expect one positional argument: the argparse.Namespace object.

Parameters:
  • parser – the ArgumentParser instance.

  • argv – a list of strings representing the arguments. If None, sys.argv is used instead. Default is None.

  • add_help_command – if True, converts first positional argument “help” to a keyword argument so that help foo becomes foo --help and displays usage information for “foo”. Default is True.

  • output_file – A file-like object for output. If None, the resulting lines are collected and returned as a string. Default is sys.stdout.

  • errors_file – Same as output_file but for sys.stderr, and None is not accepted.

  • raw_output – If True, results are written to the output file raw, without adding whitespaces or newlines between yielded strings. Default is False.

  • completion – If True, shell tab completion is enabled. Default is True. (You will also need to install it.) See argh.completion.

  • skip_unknown_args – If True, unknown arguments do not cause an error (ArgumentParser.parse_known_args is used).

  • namespace – An argparse.Namespace-like object. By default an argh.dispatching.ArghNamespace object is used. Please note that support for combined default and nested functions may be broken if a different type of object is forced.

By default the exceptions are not wrapped and will propagate. The only exception that is always wrapped is CommandError which is interpreted as an expected event so the traceback is hidden. You can also mark arbitrary exceptions as “wrappable” by using the wrap_errors() decorator.

Wrapped exceptions, or other “expected errors” like parse failures, will cause a SystemExit to be raised.

argh.dispatch_command(function, *args, **kwargs)

A wrapper for dispatch() that creates a one-command parser. Uses argh.constants.PARSER_FORMATTER.

This:

dispatch_command(foo)

…is a shortcut for:

parser = ArgumentParser()
set_default_command(parser, foo)
dispatch(parser)

This function can be also used as a decorator:

@dispatch_command
def main(foo=123):
    return foo + 1
argh.dispatch_commands(functions, *args, **kwargs)

A wrapper for dispatch() that creates a parser, adds commands to the parser and dispatches them. Uses PARSER_FORMATTER.

This:

dispatch_commands([foo, bar])

…is a shortcut for:

parser = ArgumentParser()
add_commands(parser, [foo, bar])
dispatch(parser)
argh.expects_obj(func)

Marks given function as expecting a namespace object.

Usage:

@arg('bar')
@arg('--quux', default=123)
@expects_obj
def foo(args):
    yield args.bar, args.quux

This is equivalent to:

def foo(bar, quux=123):
    yield bar, quux

In most cases you don’t need this decorator.

argh.named(new_name)

Sets given string as command name instead of the function name. The string is used verbatim without further processing.

Usage:

@named('load')
def do_load_some_stuff_and_keep_the_original_function_name(args):
    ...

The resulting command will be available only as load. To add aliases without renaming the command, check aliases().

New in version 0.19.

argh.safe_input(prompt)

Deprecated since version 0.28: This function will be removed in Argh v.0.30. Please use the built-in function input() instead.

argh.set_default_command(parser, function)

Sets default command (i.e. a function) for given parser.

If parser.description is empty and the function has a docstring, it is used as the description.

Note

If there are both explicitly declared arguments (e.g. via arg()) and ones inferred from the function signature, declared ones will be merged into inferred ones. If an argument does not conform to the function signature, AssemblingError is raised.

Note

If the parser was created with add_help=True (which is by default), option name -h is silently removed from any argument.

argh.wrap_errors(errors=None, processor=None, *args)

Decorator. Wraps given exceptions into CommandError. Usage:

@wrap_errors([AssertionError])
def foo(x=None, y=None):
    assert x or y, 'x or y must be specified'

If the assertion fails, its message will be correctly printed and the stack hidden. This helps to avoid boilerplate code.

Parameters:
  • errors – A list of exception classes to catch.

  • processor

    A callable that expects the exception object and returns a string. For example, this renders all wrapped errors in red colour:

    from termcolor import colored
    
    def failure(err):
        return colored(str(err), 'red')
    
    @wrap_errors(processor=failure)
    def my_command(...):
        ...
    

Command decorators

argh.decorators.aliases(*names)

Defines alternative command name(s) for given function (along with its original name). Usage:

@aliases('co', 'check')
def checkout(args):
    ...

The resulting command will be available as checkout, check and co.

New in version 0.19.

argh.decorators.arg(*args, **kwargs)

Declares an argument for given function. Does not register the function anywhere, nor does it modify the function in any way.

The signature of the decorator matches that of argparse.ArgumentParser.add_argument(), only some keywords are not required if they can be easily guessed (e.g. you don’t have to specify type or action when an int or bool default value is supplied).

Typical use cases:

  • In combination with expects_obj() (which is not recommended);

  • in combination with ordinary function signatures to add details that cannot be expressed with that syntax (e.g. help message).

Usage:

from argh import arg

@arg('path', help='path to the file to load')
@arg('--format', choices=['yaml','json'])
@arg('-v', '--verbosity', choices=range(0,3), default=2)
def load(path, something=None, format='json', dry_run=False, verbosity=1):
    loaders = {'json': json.load, 'yaml': yaml.load}
    loader = loaders[args.format]
    data = loader(args.path)
    if not args.dry_run:
        if verbosity < 1:
            print('saving to the database')
        put_to_database(data)

In this example:

  • path declaration is extended with help;

  • format declaration is extended with choices;

  • dry_run declaration is not duplicated;

  • verbosity is extended with choices and the default value is overridden. (If both function signature and @arg define a default value for an argument, @arg wins.)

Note

It is recommended to avoid using this decorator unless there’s no way to tune the argument’s behaviour or presentation using ordinary function signatures. Readability counts, don’t repeat yourself.

argh.decorators.expects_obj(func)

Marks given function as expecting a namespace object.

Usage:

@arg('bar')
@arg('--quux', default=123)
@expects_obj
def foo(args):
    yield args.bar, args.quux

This is equivalent to:

def foo(bar, quux=123):
    yield bar, quux

In most cases you don’t need this decorator.

argh.decorators.named(new_name)

Sets given string as command name instead of the function name. The string is used verbatim without further processing.

Usage:

@named('load')
def do_load_some_stuff_and_keep_the_original_function_name(args):
    ...

The resulting command will be available only as load. To add aliases without renaming the command, check aliases().

New in version 0.19.

argh.decorators.wrap_errors(errors=None, processor=None, *args)

Decorator. Wraps given exceptions into CommandError. Usage:

@wrap_errors([AssertionError])
def foo(x=None, y=None):
    assert x or y, 'x or y must be specified'

If the assertion fails, its message will be correctly printed and the stack hidden. This helps to avoid boilerplate code.

Parameters:
  • errors – A list of exception classes to catch.

  • processor

    A callable that expects the exception object and returns a string. For example, this renders all wrapped errors in red colour:

    from termcolor import colored
    
    def failure(err):
        return colored(str(err), 'red')
    
    @wrap_errors(processor=failure)
    def my_command(...):
        ...
    

Assembling

Functions and classes to properly assemble your commands in a parser.

argh.assembling.SUPPORTS_ALIASES = True

Deprecated since version 0.28.0: This constant will be removed in Argh v.0.30.

It’s not relevant anymore because it’s always True for all Python versions currently supported by Argh.

argh.assembling.add_commands(parser, functions, namespace=None, namespace_kwargs=None, func_kwargs=None, title=None, description=None, help=None)

Adds given functions as commands to given parser.

Parameters:
  • parser – an argparse.ArgumentParser instance.

  • functions – a list of functions. A subparser is created for each of them. If the function is decorated with arg(), the arguments are passed to argparse.ArgumentParser.add_argument(). See also dispatch() for requirements concerning function signatures. The command name is inferred from the function name. Note that the underscores in the name are replaced with hyphens, i.e. function name “foo_bar” becomes command name “foo-bar”.

  • namespace – an optional string representing the group of commands. For example, if a command named “hello” is added without the namespace, it will be available as “prog.py hello”; if the namespace if specified as “greet”, then the command will be accessible as “prog.py greet hello”. The namespace itself is not callable, so “prog.py greet” will fail and only display a help message.

  • func_kwargs – a dict of keyword arguments to be passed to each nested ArgumentParser instance created per command (i.e. per function). Members of this dictionary have the highest priority, so a function’s docstring is overridden by a help in func_kwargs (if present).

  • namespace_kwargs – a dict of keyword arguments to be passed to the nested ArgumentParser instance under given namespace.

Deprecated params that should be moved into namespace_kwargs:

Parameters:
  • title

    Deprecated since version 0.26.0: This argument will be removed in Argh v.0.30. Please use namespace_kwargs instead.

  • description

    Deprecated since version 0.26.0: This argument will be removed in Argh v.0.30. Please use namespace_kwargs instead.

  • help

    Deprecated since version 0.26.0: This argument will be removed in Argh v.0.30. Please use namespace_kwargs instead.

Note

This function modifies the parser object. Generally side effects are bad practice but we don’t seem to have any choice as ArgumentParser is pretty opaque. You may prefer add_commands() for a bit more predictable API.

Note

An attempt to add commands to a parser which already has a default function (e.g. added with set_default_command()) results in AssemblingError.

argh.assembling.add_subcommands(parser, namespace, functions, **namespace_kwargs)

A wrapper for add_commands().

These examples are equivalent:

add_commands(parser, [get, put], namespace='db',
             namespace_kwargs={
                 'title': 'database commands',
                 'help': 'CRUD for our silly database'
             })

add_subcommands(parser, 'db', [get, put],
                title='database commands',
                help='CRUD for our silly database')
argh.assembling.set_default_command(parser, function)

Sets default command (i.e. a function) for given parser.

If parser.description is empty and the function has a docstring, it is used as the description.

Note

If there are both explicitly declared arguments (e.g. via arg()) and ones inferred from the function signature, declared ones will be merged into inferred ones. If an argument does not conform to the function signature, AssemblingError is raised.

Note

If the parser was created with add_help=True (which is by default), option name -h is silently removed from any argument.

Dispatching

class argh.dispatching.ArghNamespace(*args, **kwargs)

A namespace object which collects the stack of functions.

class argh.dispatching.EntryPoint(name=None, parser_kwargs=None)

An object to which functions can be attached and then dispatched.

When called with an argument, the argument (a function) is registered at this entry point as a command.

When called without an argument, dispatching is triggered with all previously registered commands.

Usage:

from argh import EntryPoint

app = EntryPoint('main', dict(description='This is a cool app'))

@app
def ls():
    for i in range(10):
        print i

@app
def greet():
    print 'hello'

if __name__ == '__main__':
    app()
argh.dispatching.PARSER_FORMATTER

alias of CustomFormatter

argh.dispatching.dispatch(parser, argv=None, add_help_command=True, completion=True, pre_call=None, output_file=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, errors_file=<_io.TextIOWrapper name='<stderr>' mode='w' encoding='utf-8'>, raw_output=False, namespace=None, skip_unknown_args=False)

Parses given list of arguments using given parser, calls the relevant function and prints the result.

The target function should expect one positional argument: the argparse.Namespace object.

Parameters:
  • parser – the ArgumentParser instance.

  • argv – a list of strings representing the arguments. If None, sys.argv is used instead. Default is None.

  • add_help_command – if True, converts first positional argument “help” to a keyword argument so that help foo becomes foo --help and displays usage information for “foo”. Default is True.

  • output_file – A file-like object for output. If None, the resulting lines are collected and returned as a string. Default is sys.stdout.

  • errors_file – Same as output_file but for sys.stderr, and None is not accepted.

  • raw_output – If True, results are written to the output file raw, without adding whitespaces or newlines between yielded strings. Default is False.

  • completion – If True, shell tab completion is enabled. Default is True. (You will also need to install it.) See argh.completion.

  • skip_unknown_args – If True, unknown arguments do not cause an error (ArgumentParser.parse_known_args is used).

  • namespace – An argparse.Namespace-like object. By default an argh.dispatching.ArghNamespace object is used. Please note that support for combined default and nested functions may be broken if a different type of object is forced.

By default the exceptions are not wrapped and will propagate. The only exception that is always wrapped is CommandError which is interpreted as an expected event so the traceback is hidden. You can also mark arbitrary exceptions as “wrappable” by using the wrap_errors() decorator.

Wrapped exceptions, or other “expected errors” like parse failures, will cause a SystemExit to be raised.

argh.dispatching.dispatch_command(function, *args, **kwargs)

A wrapper for dispatch() that creates a one-command parser. Uses argh.constants.PARSER_FORMATTER.

This:

dispatch_command(foo)

…is a shortcut for:

parser = ArgumentParser()
set_default_command(parser, foo)
dispatch(parser)

This function can be also used as a decorator:

@dispatch_command
def main(foo=123):
    return foo + 1
argh.dispatching.dispatch_commands(functions, *args, **kwargs)

A wrapper for dispatch() that creates a parser, adds commands to the parser and dispatches them. Uses PARSER_FORMATTER.

This:

dispatch_commands([foo, bar])

…is a shortcut for:

parser = ArgumentParser()
add_commands(parser, [foo, bar])
dispatch(parser)

Interaction

argh.interaction.confirm(action, default=None, skip=False)

A shortcut for typical confirmation prompt.

Parameters:
  • action – a string describing the action, e.g. “Apply changes”. A question mark will be appended.

  • defaultbool or None. Determines what happens when user hits Enter without typing in a choice. If True, default choice is “yes”. If False, it is “no”. If None the prompt keeps reappearing until user types in a choice (not necessarily acceptable) or until the number of iteration reaches the limit. Default is None.

  • skipbool; if True, no interactive prompt is used and default choice is returned (useful for batch mode). Default is False.

Usage:

def delete(key, silent=False):
    item = db.get(Item, args.key)
    if confirm('Delete '+item.title, default=True, skip=silent):
        item.delete()
        print('Item deleted.')
    else:
        print('Operation cancelled.')

Returns None on KeyboardInterrupt event.

argh.interaction.safe_input(prompt)

Deprecated since version 0.28: This function will be removed in Argh v.0.30. Please use the built-in function input() instead.

Shell completion

Command and argument completion is a great way to reduce the number of keystrokes and improve user experience.

To display suggestions when you press tab, a shell must obtain choices from your program. It calls the program in a specific environment and expects it to return a list of relevant choices.

Argparse does not support completion out of the box. However, there are 3rd-party apps that do the job, such as argcomplete and python-selfcompletion.

Argh supports only argcomplete which doesn’t require subclassing the parser and monkey-patches it instead. Combining Argh with python-selfcompletion isn’t much harder though: simply use SelfCompletingArgumentParser instead of vanilla ArgumentParser.

See installation details and gotchas in the documentation of the 3rd-party app you’ve chosen for the completion backend.

Argh automatically enables completion if argcomplete is available (see COMPLETION_ENABLED). If completion is undesirable in given app by design, it can be turned off by setting completion=False in argh.dispatching.dispatch().

Note that you don’t have to add completion via Argh; it doesn’t matter whether you let it do it for you or use the underlying API.

Argument-level completion

Argcomplete supports custom “completers”. The documentation suggests adding the completer as an attribute of the argument parser action:

parser.add_argument("--env-var1").completer = EnvironCompleter

However, this doesn’t fit the normal Argh-assisted workflow. It is recommended to use the arg() decorator:

@arg('--env-var1', completer=EnvironCompleter)
def func(...):
    ...
argh.completion.COMPLETION_ENABLED = False

Dynamically set to True on load if argcomplete was successfully imported.

argh.completion.autocomplete(parser)

Adds support for shell completion via argcomplete by patching given argparse.ArgumentParser (sub)class.

If completion is not enabled, logs a debug-level message.

Helpers

class argh.helpers.ArghParser(*args, **kwargs)

A subclass of argparse.ArgumentParser with support for and a couple of convenience methods.

All methods are but wrappers for stand-alone functions add_commands(), autocomplete() and dispatch().

Uses PARSER_FORMATTER.

add_commands(*args, **kwargs)

Wrapper for add_commands().

autocomplete()

Wrapper for autocomplete().

dispatch(*args, **kwargs)

Wrapper for dispatch().

parse_args(args=None, namespace=None)

Wrapper for argparse.ArgumentParser.parse_args(). If namespace is not defined, argh.dispatching.ArghNamespace is used. This is required for functions to be properly used as commands.

set_default_command(*args, **kwargs)

Wrapper for set_default_command().

Exceptions

exception argh.exceptions.AssemblingError

Raised if the parser could not be configured due to malformed or conflicting command declarations.

exception argh.exceptions.CommandError(*args, code=None)

Intended to be raised from within a command. The dispatcher wraps this exception by default and prints its message without traceback, then exits with exit code 1.

Useful for print-and-exit tasks when you expect a failure and don’t want to startle the ordinary user by the cryptic output.

Consider the following example:

def foo(args):
    try:
        ...
    except KeyError as e:
        print(u'Could not fetch item: {0}'.format(e))
        sys.exit(1)

It is exactly the same as:

def bar(args):
    try:
        ...
    except KeyError as e:
        raise CommandError(u'Could not fetch item: {0}'.format(e))

To customize the exit status, pass an integer (as per sys.exit()) to the code keyword arg.

This exception can be safely used in both print-style and yield-style commands (see Tutorial).

exception argh.exceptions.DispatchingError

Raised if the dispatching could not be completed due to misconfiguration which could not be determined on an earlier stage.

Output Processing

argh.io.safe_input(prompt)

Deprecated since version 0.28: This function will be removed in Argh v.0.30. Please use the built-in function input() instead.

Utilities

argh.utils.get_arg_spec(function)

Returns argument specification for given function. Omits special arguments of instance methods (self) and static methods (usually cls or something like this).

argh.utils.get_subparsers(parser, create=False)

Returns the argparse._SubParsersAction instance for given argparse.ArgumentParser instance as would have been returned by argparse.ArgumentParser.add_subparsers(). The problem with the latter is that it only works once and raises an exception on the second attempt, and the public API seems to lack a method to get existing subparsers.

Parameters:

create – If True, creates the subparser if it does not exist. Default if False.

argh.utils.unindent(text)

Given a multi-line string, decreases indentation of all lines so that the first non-empty line has zero indentation and the remaining lines are adjusted accordingly.

Constants

argh.constants.ATTR_ALIASES = 'argh_aliases'

alternative command names

argh.constants.ATTR_ARGS = 'argh_args'

declared arguments

argh.constants.ATTR_EXPECTS_NAMESPACE_OBJECT = 'argh_expects_namespace_object'

forcing argparse.Namespace object instead of signature introspection

argh.constants.ATTR_NAME = 'argh_name'

explicit command name (differing from function name)

argh.constants.ATTR_WRAPPED_EXCEPTIONS = 'argh_wrap_errors'

list of exception classes that should be wrapped and printed as results

argh.constants.ATTR_WRAPPED_EXCEPTIONS_PROCESSOR = 'argh_wrap_errors_processor'

a function to preprocess the exception object when it is wrapped

class argh.constants.CustomFormatter(prog, indent_increment=2, max_help_position=24, width=None)

A slightly customised argparse.ArgumentDefaultsHelpFormatter + argparse.RawDescriptionHelpFormatter.

argh.constants.DEFAULT_ARGUMENT_TEMPLATE = '%(default)s'

Default template of argument help message (see issue #64). The template %(default)s is used by argparse to display the argument’s default value.

argh.constants.DEST_FUNCTION = 'function'

dest name for a function mapped to given endpoint (goes to Namespace obj)

argh.constants.PARSER_FORMATTER

Default formatter (CustomFormatter) to be used in implicitly instantiated ArgumentParser.