API Reference

Command decorators

argh.decorators.alias(new_name)

Deprecated since version 0.19.

Use named() or aliases() instead.

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.

Note

This decorator only works with a recent version of argparse (see Python issue 9324 and Python rev 4c0426). Such version ships with Python 3.2+ and may be available in other environments as a separate package. Argh does not issue warnings and simply ignores aliases if they are not supported. See SUPPORTS_ALIASES.

New in version 0.19.

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.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 is exactly the same as that of argparse.ArgumentParser.add_argument(), only some keywords are not required if they can be easily guessed.

Usage:

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

Note that:

  • you didn’t have to specify action="store_true" for --dry-run;
  • you didn’t have to specify type=int for --verbosity.
argh.decorators.plain_signature(func)

Deprecated since version 0.20.

Function signature is now introspected by default. Use expects_obj() for inverted behaviour.

argh.decorators.command(func)

Deprecated since version 0.21.

Function signature is now introspected by default. Use expects_obj() for inverted behaviour.

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(...):
        ...
    

Warning

The exceptions argument must be a list.

For backward compatibility reasons the old way is still allowed:

@wrap_errors(KeyError, ValueError)

However, the hack that allows that will be removed in Argh 1.0.

Please make sure to update your code.

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.

Assembling

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

argh.assembling.SUPPORTS_ALIASES = False

Calculated on load. If True, current version of argparse supports alternative command names (can be set via aliases()).

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

An attempt to set default command to a parser which already has subparsers (e.g. added with add_commands()) results in a RuntimeError.

Note

If there are both explicitly declared arguments (e.g. via arg()) and ones inferred from the function signature (e.g. via command()), declared ones will be merged into inferred ones. If an argument does not conform function signature, ValueError 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.assembling.add_commands(parser, functions, namespace=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.

Help message for a namespace can be also tuned with these params (provided that you specify the namespace):

Parameters:
  • title – passed to argparse.ArgumentParser.add_subparsers() as title.
  • description – passed to argparse.ArgumentParser.add_subparsers() as description.
  • help – passed to argparse.ArgumentParser.add_subparsers() as help.

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.

Design flaw

This function peeks into the parser object using its internal API. Unfortunately the public API does not allow to get the subparsers, it only lets you add them, and do that once. So you would have to toss the subparsers object around to add something later. That said, I doubt that argparse will change a lot in the future as it’s already pretty stable. If some implementation details would change and break argh, we’ll simply add a workaround a keep it compatibile.

Note

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

Dispatching

argh.dispatching.dispatch(parser, argv=None, add_help_command=True, completion=True, pre_call=None, output_file=<open file '<stdout>', mode 'w' at 0x7fed9d3cb150>, errors_file=<open file '<stderr>', mode 'w' at 0x7fed9d3cb1e0>, raw_output=False, namespace=None)

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. However, if the function is decorated with plain_signature(), the positional and named arguments from the namespace object are passed to the function instead of the object itself.

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.
  • 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.

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.

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

A wrapper for dispatch() that creates a one-command parser. Uses 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.

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)
argh.dispatching.PARSER_FORMATTER

alias of ArgumentDefaultsHelpFormatter

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)

Prompts user for input. Correctly handles prompt message encoding.

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.autocomplete(parser)

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

argh.completion.COMPLETION_ENABLED = True

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

Helpers

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

A subclass of ArgumentParser with a couple of convenience methods.

There is actually no need to subclass the parser. The methods are but wrappers for stand-alone functions add_commands(), autocomplete() and dispatch().

Uses PARSER_FORMATTER.

add_commands(*args, **kwargs)

Wrapper for add_commands().

dispatch(*args, **kwargs)

Wrapper for dispatch().

set_default_command(*args, **kwargs)

Wrapper for set_default_command().

Exceptions

exception argh.exceptions.CommandError

The only exception that is wrapped by the dispatcher. Useful for print-and-exit tasks.

Consider the following example:

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

It is exactly the same as:

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

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

Output Processing

argh.io.dump(raw_data, output_file)

Writes given line to given output file. See encode_output() for details.

argh.io.encode_output(value, output_file)

Encodes given value so it can be written to given file object.

Value may be Unicode, binary string or any other data type.

The exact behaviour depends on the Python version:

Python 3.x

sys.stdout is a _io.TextIOWrapper instance that accepts str (unicode) and breaks on bytes.

It is OK to simply assume that everything is Unicode unless special handling is introduced in the client code.

Thus, no additional processing is performed.

Python 2.x

sys.stdout is a file-like object that accepts str (bytes) and breaks when unicode is passed to sys.stdout.write().

We can expect both Unicode and bytes. They need to be encoded so as to match the file object encoding.

The output is binary if the object doesn’t explicitly require Unicode.

argh.io.safe_input(prompt)

Prompts user for input. Correctly handles prompt message encoding.

Utilities

argh.utils.get_arg_names(function)

Returns argument names 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 ArgumentParser instance as would have been returned by 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.

Table Of Contents

Previous topic

Tutorial

Next topic

Similar projects

This Page