cli: Application command line support

This module provides a method for parsing text commands and calling the functions that implement them. First, commands are registered with a description of the arguments they take, and with a function that implements the command. Later, a Command instance is used to parse a command line, and optionally execute the command. Incomplete command lines are supported, so possible commands can be suggested.

In addition to registering command functions, there is a separate mechanism to support textual Command Aliases.

Text Commands

Synopsis:

command_name rv1 rv2 [ov1 [ov2]] [kn1 kv1] [kn2 kv2]

Text commands are composed of a command name, which can be multiple words, followed by required positional arguments, rvX, optional positional arguments, ovX, and keyword arguments with a value, knX kvX. Each argument has an associated Python argument name (for keyword arguments it is the keyword, knX). rvX, ovX, and kvX are the type-checked values. If the argument name is the same as a Python keyword, then an underscore appended to it to form the Python argument name. The names of the optional arguments are used to let them be given as keyword arguments as well. Multiple value arguments are separated by commas and the commas may be followed by whitespace. Depending on the type of an argument, e.g., a color name, whitespace can also appear within an argument value. Argument values may be quoted with double quotes. And in quoted text, Python’s textual escape sequences are recognized, e.g., \N{LATIN CAPITAL LETTER A WITH RING ABOVE} for the ångström sign, Å.

Words in the command name may be truncated and are automatically completed to the first registered command with the given prefix. Likewise for keyword arguments.

Keywords are case sensitive, and are expected to be all lowercase. Underscores are elided, but are documented as mixed case. For example, a bg_color keyword would be documented as bgColor.

Registering Commands

To add a command, register() the command name, a description of the arguments it takes, and the function to call that implements the command. Command registration can be partially delayed to avoid importing the command description and function until needed. See register() and delay_registration() for details.

The description is either an instance of the Command Description class, CmdDesc, or a tuple with the arguments to the initializer. The CmdDesc initializer takes tuples describing the required, optional, and keyword arguments. Each tuple contains tuples with the argument name and a type annotation (see below). Postconditions (see below) can be given too.

Command Functions

The command function arguments are expected to start with a session argument. The rest of the arguments are assembled as keyword arguments, as built from the command line and the command description. The initial session argument to a command function is not part of the command description.

Type Annotations

There are many standard type notations and they should be reused as much as possible:

Type Annotation
bool BoolArg
float FloatArg
int IntArg
str StringArg
tuple of 3 bool Bool3Arg
tuple of 3 float Float3Arg
tuple of 3 int Int3Arg
list of float FloatsArg
list of int IntsArg

There is one special annotation: RestOfLine that consumes the rest of the command line as text.

Annotations are used to parse text and convert it to the appropriate type. Annotations can be extended with various specializers:

Specializer Example
Bounded Bounded(FloatArg, 0.0, 100.0)
ListOf ListOf(FloatArg) a.k.a., FloatsArg
SetOf SetOf(IntArg)
TupleOf TupleOf(FloatArg, 3) a.k.a., Float3Arg
Or Or(FloatArg, StringArg) discouraged
EnumOf enumerated values

Creating Your Own Type Annotation

Annotations perform several functions: (1) to convert text to a value of the appropriate type, and (2) to give reasonable error messages.

See the Annotation documentation for details.

Example

Here is a simple example:

import from chimerax.core.commands import Command, CmdDesc, RestOfLine
import from chimerax.core import errors
@register("echo", CmdDesc(optional=[('text', RestOfLine)]))
def echo(session, text=''):
    print(text)
...
command = Command(session)
try:
    status = command.run(text)
    if status:
        print(status)
except errors.UserError as err:
    print(err, file=sys.stderr)

Command Aliases

Normally, command aliases are made with the alias command, but they can also be explicitly register with alias() and removed with remove_alias().

An alias definition uses $n to refer to passed in arguments. $1 may appear more than once. $$ is $.

To register a multiword alias, quote the command name.

class Aggregate(annotation, min_size=None, max_size=None, name=None, url=None, prefix=None)

Bases: chimerax.core.commands.cli.Annotation

Common class for collections of values.

Aggregate(annotation, constructor, add_to, min_size=None, max_size=None,
name=None, url=None) -> annotation
Parameters:
  • annotation – annotation for values in the collection.
  • min_size – minimum size of collection, default None.
  • max_size – maximum size of collection, default None.
  • name – optionally override name in error messages.
  • url – optionally give documentation URL.
  • prefix – optionally required prefix to aggregate.

This class is typically used via ListOf, SetOf, or TupleOf. The comma separator for aggregate values is handled by the Command class, so parsing is delegated to the underlying annotation.

Subclasses need to set the constructor attribute and replace the add_to method.

add_to(container, element)

Add to add an element to the container

Parameters:
  • container – the container to add elements to
  • element – the element to add to the container
Returns:

None for mutable containers, or a new container if immutable.

class Alias(text, *, user=False)

Bases: object

alias a command

Returns a callable unnamed command alias.

Parameters:
  • text – parameterized command text
  • user – true if alias was generated by user

The text is scanned for $n, where n is the n-th argument, $* for the rest of the line, and $$ for a single $.

cmd_desc(**kw)

Return CmdDesc instance for alias

The CmdDesc keyword arguments other than ‘required’, ‘optional’, and ‘keyword’ can be used.

class Annotation(name=None, url=None, html_name=None)

Bases: object

Base class for all annotations

Each annotation should have the following attributes:

name

Set to textual description of the annotation, including the leading article, e.g., “an integer”.

inst_html_name(name=None)

Subclasses that are to be used as instances, should set their html_name method to be Annotation.inst_html_name

name = None

article name, e.g., “an integer”

static parse(text, session)

Convert text to appropriate type.

Parameters:
  • text – command line text to parse
  • session – for session-dependent data types
Returns:

3-tuple with the converted value, consumed text (possibly altered with expanded abbreviations), and the remaining unconsumed text

Raises:

ValueError – if unable to convert text

The leading space in text must already be removed. It is up to the particular annotation to support abbreviations.

Empty text should raise a ValueError or AnnotationError exception (the exceptions being NoArg and EmptyArg).

url = None

URL for help information

exception AnnotationError(message, offset=None)

Bases: chimerax.core.errors.UserError, ValueError

Error, with optional offset, in annotation

class AtomicStructuresArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command atomic structures specifier

class AtomsArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command atoms specifier

class AxisArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for axis vector that can be 3 floats or “x”, or “y”, or “z” or two atoms.

class BondsArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.ObjectsArg

Parse command specifier for bonds

class BoolArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for boolean literals

class Bounded(annotation, min=None, max=None, name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Support bounded numerical values

Bounded(annotation, min=None, max=None, name=None, url=None) -> an Annotation

Parameters:
  • annotation – numerical annotation
  • min – optional lower bound
  • max – optional upper bound
  • name – optional explicit name for annotation
  • url – optionally give documentation URL.
class CenterArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for a center point that can be 3 floats or objects.

class CmdDesc(required=(), optional=(), keyword=(), postconditions=(), required_arguments=(), non_keyword=(), hidden=(), url=None, synopsis=None)

Bases: object

Describe command arguments.

Parameters:
  • required – required positional arguments sequence
  • optional – optional positional arguments sequence
  • keyword – keyword arguments sequence
  • required_arguments – sequence of argument names that must be given
  • non_keyword – sequence of optional arguments that cannot be keywords
  • hidden – sequence of keyword arguments that should be omitted from usage
  • url – URL to help page
  • synopsis – one line description

Each :param required:, :param optional:, :param keyword: sequence contains 2-tuples with the argument name and a type annotation. The command line parser uses the :param optional: argument names as additional keyword arguments. :param required_arguments: are for Python function arguments that don’t have default values, but should be given on the command line (typically keyword arguments, but could be used for syntactically optional arguments).

copy()

Return a copy suitable for use with another function.

class Command(session)

Bases: object

Keep track of (partially) typed command with possible completions

Parameters:session – the session to run the command in (may be None for testing)
run(text, *, log=True, _used_aliases=None)

Parse and execute commands in the text

Parameters:
  • text – The text to be parsed.
  • log – True (default) if commands are logged.

There are a couple side effects:

  • The automatically completed text is put in self.current_text.
  • Possible completions are in self.completions.
  • The prefix of the completions is in self.completion_prefix.
class CoordSysArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.ModelArg

Annotation for coordinate system for AxisArg and CenterArg when specified as tuples of numbers. Coordinate system is specified as a Model specifier.

class DottedTupleOf(annotation, min_size=None, max_size=None, name=None, url=None, prefix=None)

Bases: chimerax.core.commands.cli.Aggregate

Annotation for dot-separated lists of a single type

DottedListOf(annotation, min_size=None, max_size=None) -> annotation

constructor

alias of tuple

class DynamicEnum(values_func, name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Enumerated type where enumeration values computed from a function.

class EmptyArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for optionally missing ‘required’ argument

class EnumOf(values, ids=None, abbreviations=None, name=None, url=None)

Bases: chimerax.core.commands.cli.Annotation

Support enumerated types

EnumOf(values, ids=None, name=None, url=None) -> an Annotation

Parameters:
  • values – iterable of values
  • ids – optional iterable of identifiers
  • abbreviations – if not None, then override allow_truncated
  • name – optional explicit name for annotation
  • url – optionally give documentation URL.

If the ids are given, then there must be one for each and every value, otherwise the values are used as the identifiers. The identifiers must all be strings.

class FileNameArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Base class for Open/SaveFileNameArg

class FloatArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for floating point literals

class IntArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for integer literals

class Limited(arg_name, min=None, max=None)

Bases: chimerax.core.commands.cli.Postcondition

Bounded numerical values postcondition

Limited(name, min=None, max=None) -> Postcondition

Parameters:
  • arg_name – name of argument to check
  • min – optional inclusive lower bound
  • max – optional inclusive upper bound

If possible, use the Bounded annotation because the location of the error is the beginning of the argument, not the end of the line.

class ListOf(annotation, min_size=None, max_size=None, name=None, url=None, prefix=None)

Bases: chimerax.core.commands.cli.Aggregate

Annotation for lists of a single type

ListOf(annotation, min_size=None, max_size=None) -> annotation

constructor

alias of list

class ModelArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command model specifier

class ModelsArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command models specifier

class NoArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for keyword whose presence indicates True

class NoneArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for ‘none’ (typically used with Or)

class ObjectsArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command objects specifier

class OpenFileNameArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.FileNameArg

Annotation for a file to open

class OpenFolderNameArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.FileNameArg

Annotation for a folder to open from

class Or(*annotations, name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Support two or more alternative annotations

Or(annotation, annotation [, annotation]*, name=None, url=None) -> an Annotation

Parameters:
  • name – optional explicit name for annotation
  • url – optionally give documentation URL.
class PasswordArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.StringArg

Annotation for a password (should not be echoed to log)

class PlaceArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for positioning matrix as 12 floats defining a 3 row, 4 column matrix where the first 3 columns are x,y,z coordinate axes, and the last column is the origin.

class Postcondition

Bases: object

Base class for postconditions

check(kw_args)

Assert arguments match postcondition

Parameters:kw_args – dictionary of arguments that will be passed to command callback function.
Returns:True if arguments are consistent
error_message()

Appropriate error message if check fails.

Returns:error message
class PseudobondGroupsArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command atom specifier for pseudobond groups

class PseudobondsArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.ObjectsArg

Parse command specifier for pseudobonds

class RepeatOf(annotation)

Bases: chimerax.core.commands.cli.Annotation

Annotation for keyword options that can occur multiple times.

RepeatOf(annotation) -> annotation

Option values are put in list even if option occurs only once.

class RestOfLine(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Return the rest of the line up to a semicolon

class SameSize(name1, name2)

Bases: chimerax.core.commands.cli.Postcondition

Postcondition check for same size arguments

SameSize(name1, name2) -> a SameSize object

Parameters:
  • name1 – name of first argument to check
  • name2 – name of second argument to check
class SaveFileNameArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.FileNameArg

Annotation for a file to save

class SaveFolderNameArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.FileNameArg

Annotation for a folder to save to

class SetOf(annotation, min_size=None, max_size=None, name=None, url=None, prefix=None)

Bases: chimerax.core.commands.cli.Aggregate

Annotation for sets of a single type

SetOf(annotation, min_size=None, max_size=None) -> annotation

constructor

alias of set

class StringArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Annotation for text (a word or quoted)

class StructureArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.ModelArg

Parse command structure specifier

class StructuresArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command structures specifier

class SurfacesArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command surfaces specifier

class TopModelsArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command models specifier

class TupleOf(annotation, size, name=None, url=None)

Bases: chimerax.core.commands.cli.Aggregate

Annotation for tuples of a single type

TupleOf(annotation, size) -> annotation

constructor

alias of tuple

class UniqueChainsArg(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.atomspec.AtomSpecArg

Parse command atoms specifier

class WholeRestOfLine(name=None, url=None, html_name=None)

Bases: chimerax.core.commands.cli.Annotation

Return the whole rest of the line including semicolons

add_keyword_arguments(name, kw_info)

Make known additional keyword argument(s) for a command

Parameters:
  • name – the name of the command (must not be an alias)
  • kw_info – { keyword: annotation }
command_function(name, no_aliases=False)

Return callable for given command name

Parameters:
  • name – the name of the command
  • no_aliases – True if aliases should not be considered.
Returns:

the callable that implements the command

command_url(name, no_aliases=False)

Return help URL for given command name

Parameters:
  • name – the name of the command
  • no_aliases – True if aliases should not be considered.
Returns:

the URL registered with the command

commas(text_seq, conjunction=' or')

Return comma separated list of words

Parameters:
  • text_seq – a sequence of text strings
  • conjunction – a word with a leading space
create_alias(name, text, *, user=False, logger=None, url=None)

Create command alias

Parameters:
  • name – name of the alias
  • text – text of the alias
  • user – boolean, true if user created alias
  • logger – optional logger
delay_registration(name, proxy_function, logger=None)

delay registering a named command until needed

Parameters:
  • proxy_function – the function to call if command is used
  • logger – optional logger

The proxy function should explicitly reregister the command or register subcommands and return nothing.

Example:

from chimerax.core.commands import cli

def lazy_reg():
    import module
    cli.register('cmd subcmd1', module.subcmd1_desc, module.subcmd1)
    cli.register('cmd subcmd2', module.subcmd2_desc, module.subcmd2)

cli.delay_registration('cmd', lazy_reg)
deregister(name, *, is_user_alias=False, parent_info=None)

Remove existing command and subcommands

Parameters:name – the name of the command

If the command was an alias, the previous version is restored

discard_article(text)

remove leading article from text

dq_repr(obj)

Like repr, but use double quotes

expand_alias(name)

Return text of named alias

Parameters:name – name of the alias
html_usage(name, no_aliases=False, show_subcommands=5, expand_alias=True, show_hidden=False)

Return usage string in HTML for given command name

Parameters:
  • name – the name of the command
  • no_aliases – True if aliases should not be considered.
  • show_subcommands – number of subcommands that should be shown.
  • show_hidden – True if hidden keywords should be shown.
Returns:

a HTML usage string for the command

is_python_keyword()

x.__contains__(y) <==> y in x.

list_aliases(all=False, logger=None)

List all aliases

Parameters:all – if True, then only list all aliases, not just user ones

Return in depth-first order.

next_token(text, *, no_raise=False)

Extract next token from given text.

Parameters:text – text to parse without leading whitespace
Returns:a 3-tuple of first argument in text, the actual text used, and the rest of the text.

Tokens may be quoted, in which case the text between the quotes is returned.

ordinal(i)

Return ordinal number name of number

plural_form(seq, word, plural=None)

Return plural of word based on length of sequence

Parameters:
  • seq – a sequence of objects
  • word – word to form the plural of
  • plural – optional explicit plural of word, otherwise best guess
plural_of(word)

Return best guess of the American English plural of the word

Parameters:word – the word to form the plural version

The guess is rudimentary, e.g., it does not handle changing “leaf” to “leaves”. So in general, use the plural_form() function and explicitly give the plural.

register(name, cmd_desc=(), function=None, *, logger=None, parent_info=None)

register function that implements command

Parameters:
  • name – the name of the command and may include spaces.
  • cmd_desc – information about the command, either an instance of CmdDesc, or the tuple with CmdDesc parameters.
  • function – the callback function.
  • logger – optional logger

If the function is None, then it assumed that register() is being used as a decorator.

To delay introspecting the function until it is actually used, register using the delay_registration() function.

For autocompletion, the first command registered with a given prefix wins. Registering a command that is a prefix of an existing command is an error since it breaks backwards compatibility.

registered_commands(multiword=False, _start=None)

Return a sorted list of the currently registered commands

remove_alias(name=None, user=False, logger=None)

Remove command alias

Parameters:
  • name – name of the alias
  • user – boolean, true if user created alias

If no name is given, then all user generated aliases are removed.

unescape(text)

Replace backslash escape sequences with actual character.

Parameters:text – the input text
Returns:the processed text

Follows Python’s string literal syntax for escape sequences.

unescape_with_index_map(text)

Replace backslash escape sequences with actual character.

Parameters:text – the input text
Returns:the processed text and index map from processed to input text

Follows Python’s string literal syntax for escape sequences.

usage(name, no_aliases=False, show_subcommands=5, expand_alias=True, show_hidden=False)

Return usage string for given command name

Parameters:
  • name – the name of the command
  • no_aliases – True if aliases should not be considered.
  • show_subcommands – number of subcommands that should be shown.
  • show_hidden – True if hidden keywords should be shown.
Returns:

a usage string for the command