commands: Register user commands

cli: Command line interface

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. String argument values may be quoted with double or single quotes, and 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: 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)

Experimental API . 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.

parse(text, session)

Supported API . 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:

AnnotationError – 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).

unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

class Alias(text, *, user=False, registry=None)

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)

Experimental API . 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

Supported API. Base class for all annotations

Annotations encapsulate how to parse text into a particular type. Both subclasses and instances of subclasses can be used as annotations. An instance is used when an annotation is parameterized, e.g., with the length of a sequence.

Each annotation should have the following attributes:

name

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

url

URL for help information.

html_name()

A class or instance method that returns the HTML version of the name.

classmethod html_name(name=None)

Supported API . Return HTML verison of name attribute

If the url attribute is set, then a HTML href using that URL is returned.

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

classmethod unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

exception AnnotationError(message, offset=0)

Bases: UserError, ValueError

Error, with optional offset, in an annotation

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

Bases: StringArg

Annotation for a Python attribute name

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

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

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

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

Bases: Annotation

Annotation for boolean literals

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

Support bounded numerical values

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

Parameters:
  • annotation – numerical annotation

  • min – optional lower bound

  • max – optional upper bound

  • inclusive – is the bound itself in the range

  • name – optional explicit name for annotation

  • url – optionally give documentation URL.

parse(text, session)

Supported API . 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:

AnnotationError – 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).

unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

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

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

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

Bases: StringArg

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

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

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

Experimental API . Return a copy suitable for use with another function.

class Command(session, *, registry=None)

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, log_only=False, return_json=False, _used_aliases=None)

Experimental API . 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: ModelArg

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

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

classmethod unparse(value, session)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Aggregate

Annotation for dot-separated lists of a single type

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

add_to(container, value)

Experimental API . 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.

constructor

alias of tuple

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

Bases: Annotation

Enumerated type where enumeration values computed from a function.

property name

str(object=’’) -> str str(bytes_or_buffer[, encoding[, errors]]) -> str

Create a new string object from the given object. If encoding or errors is specified, then the object must expose a data buffer that will be decoded using the given encoding and error handler. Otherwise, returns the result of object.__str__() (if defined) or repr(object). encoding defaults to sys.getdefaultencoding(). errors defaults to ‘strict’.

parse(text, session)

Supported API . 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:

AnnotationError – 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).

unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

Annotation for optionally missing ‘required’ argument

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: 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.

parse(text, session)

Supported API . 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:

AnnotationError – 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).

unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

Base class for Open/SaveFileNameArg

classmethod parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

Annotation for floating point literals

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

Annotation for non-negative floating point literals, but if preceded by explicit +/- then interpreted as a delta

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

Annotation for integer literals

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: 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.

check(kw_args)

Experimental API . 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()

Experimental API . Appropriate error message if check fails.

Returns:

error message

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

Bases: Aggregate

Annotation for lists of a single type

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

add_to(container, value)

Experimental API . 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.

constructor

alias of list

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

Bases: AtomSpecArg

Parse command model specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

classmethod unparse(model, session)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: AtomSpecArg

Parse command models specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

classmethod unparse(models, session)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

Annotation for keyword whose presence indicates True

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Annotation

Annotation for ‘none’ (typically used with Or)

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: AtomSpecArg

Parse command objects specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

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

Bases: BoolArg

BoolArg, but puts ‘on or off’ in usage text instead of ‘true or false’ where it would make more grammatical sense to do so

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

Bases: FileNameArg

Annotation for a file to open

classmethod parse(text, session)

Supported API . 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:

AnnotationError – 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).

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

Bases: Annotation

Annotation for opening one or more files

classmethod parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: FileNameArg

Annotation for a folder to open from

classmethod parse(text, session)

Supported API . 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:

AnnotationError – 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).

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

Bases: 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.

parse(text, session)

Supported API . 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:

AnnotationError – 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).

unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: StringArg

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

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: 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.

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

class Postcondition

Bases: object

Base class for postconditions

check(kw_args)

Experimental API . 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()

Experimental API . Appropriate error message if check fails.

Returns:

error message

class RepeatOf(annotation)

Bases: 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: Annotation

Return the rest of the line up to a semicolon

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

class SameSize(name1, name2)

Bases: 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

check(kw_args)

Experimental API . 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()

Experimental API . Appropriate error message if check fails.

Returns:

error message

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

Bases: FileNameArg

Annotation for a file to save

classmethod parse(text, session)

Supported API . 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:

AnnotationError – 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).

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

Bases: FileNameArg

Annotation for a folder to save to

classmethod parse(text, session)

Supported API . 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:

AnnotationError – 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).

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

Bases: Aggregate

Annotation for sets of a single type

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

add_to(container, value)

Experimental API . 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.

constructor

alias of set

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

Bases: Annotation

Annotation for text (a word or quoted)

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: SurfacesArg

Parse command surfaces specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

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

Bases: ModelsArg

Parse command surfaces specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

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

Bases: AtomSpecArg

Parse command models specifier

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

classmethod unparse(tmodels, session)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

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

Bases: Aggregate

Annotation for tuples of a single type

TupleOf(annotation, size) -> annotation

add_to(container, value)

Experimental API . 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.

constructor

alias of tuple

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

Bases: Annotation

Return the whole rest of the line including semicolons

static parse(text, session)

Supported API . 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:

AnnotationError – 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).

static unparse(value, session=None)

Experimental API . Convert value to string that can parsed back into value

Parameters:
  • value – the value to convert

  • session – requried for session-dependent data types

Returns:

string version of the value

The return value should be what would be typed if the value were given on the command line.

as_parser(annotation)

Experimental API . Deprecated API. Use make_converter() instead

command_function(name, no_aliases=False, *, registry=None)

Experimental API . 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, *, registry=None)

Experimental API . 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')

Experimental API . Return comma separated list of words

Parameters:
  • text_seq – a sequence of text strings

  • conjunction – a word to put for last item (default ‘or’)

create_alias(name, text, *, user=False, logger=None, url=None, registry=None)

Experimental API . 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)

Experimental API . 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, registry=None)

Experimental API . 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)

Experimental API . remove leading article from text

dq_repr(obj)

Experimental API . Like repr, but use double quotes

expand_alias(name, *, registry=None)

Experimental API . Return text of named alias

Parameters:

name – name of the alias

is_python_keyword()

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

list_aliases(all=False, logger=None)

Experimental API . List all aliases

Parameters:

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

Return in depth-first order.

make_converter(annotation)

Supported API . Use any annotation to convert text to annotation’s type

Parameters:

annotation – the annotation to use

Raises:

AnnotationError – if unable to convert text

For example:

from chimerax.core.commands import make_converter, ColorArg convert_to_color = make_converter(ColorArg) color = convert_to_color(session, “red”)

next_token(text, convert=False)

Experimental API . Extract next, optionally quoted, token from given text.

Parameters:
  • text – text to parse without leading whitespace

  • convert – convert escape sequences to characters

Returns:

a 3-tuple of first argument in text, the actual text used, and the rest of the text.

If the token is quoted, then the text between the quotes is returned. End quotes must be followed by whitespace or the end of the line. If convert is True, then escape sequences in the token are converted to the actual character. The escape sequences are the same as Python’s as documented in Literals.

ordinal(i)

Experimental API . Return ordinal number name of number

plural_form(things, word, plural=None)

Experimental API . Return plural of word based on length of sequence

Parameters:
  • things – a sequence of objects or an integer

  • word – word to form the plural of

  • plural – optional explicit plural of word, otherwise best guess

plural_of(word)

Experimental API . 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.

quote_if_necessary(s, additional_special_map={})

Experimental API . quote a string

So StringArg treats it like a single value

quote_path_if_necessary(path)

Experimental API . quote a string

So a FileNameArg (or subclass) treats it like a singe value. String escape sequences are not recognized in paths, so there no way to quote a path so that both single and double quotes that would need quoting.

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

Experimental API . register function that implements command

Parameters:
  • name (str) – the name of the command and may include spaces.

  • cmd_desc (CmdDesc) – information about the command, either an instance of CmdDesc, or the tuple with CmdDesc parameters.

  • function (Callable[..., Any]) – the callback function.

  • logger – optional logger

Return type:

Callable[..., Any]

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

registry is a RegisteredCommandInfo instance and is only used if you want your own separate registry of commands, to be parsed/executed on text you provide. One usage scenario is a set of “subcommands” organized under an “umbrella” command, e.g.:

sequence viewer <viewer-id> command-to-viewer

The ‘command-to-viewer’ commands could have their own separate registry.

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

registered_commands(multiword=False, _start=None)

Experimental API . Return a sorted list of the currently registered commands

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

Experimental API . 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)

Experimental API . 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)

Experimental API . 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.

user_kw(kw_name)

Experimental API . Return user version of a keyword argument name.

atomspec: atom specifier cli annotation and evaluation

The ‘atomspec’ module provides two classes:

  • AtomSpecArg : command line argument annotation class.

  • AtomSpec : atom specifier class.

AtomSpecArg is a cli type annotation and is used to describe an argument of a function that is registered with the cli module. When the registered function is called, the argument corresponding to the AtomSpecArg is an instance of AtomSpec, which contains a parsed version of the input atom specifier. The model elements (atoms, bonds, models, etc) that match an AtomSpec may be found by calling the ‘evaluate’ method which returns an instance of Objects. Each type of model elements may be accessed as an attribute of the Objects instance.

Selectors

A (name, function) pair may be registered as a ‘selector’ in an atom specifier. The selectors may either be global (e.g., chemical groups) or session-specific (e.g., active site). The selector name may appear wherever a model, residue or atom string does. The selector function is called when the atom specifier is evaluated and is expected to fill in an Objects instance.

Example

Here is an example of a function that may be registered with cli:

from chimerax.core.commands import cli, atomspec

def move(session, by, modelspec=None):
    if modelspec is None:
        modelspec = atomspec.everything(session)
    spec = modelspec.evaluate(session)
    import numpy
    by_vector = numpy.array(by)
    from chimerax.geometry import place
    translation = place.translation(by_vector)
    for m in spec.models:
        m.position = translation * m.position
move_desc = cli.CmdDesc(required=[("by", cli.Float3Arg)],
                        optional=[("modelspec", atomspec.AtomSpecArg)])

Notes

AtomSpecArg arguments should always be optional because not providing an atom specifier is the same as choosing all atoms.

class AtomSpec(operator, left_spec, right_spec, *, add_implied=True)

Bases: object

AtomSpec instances store and evaluate atom specifiers.

An AtomSpec instance, returned by AtomSpecArg arguments in cli command functions, keeps track of an atom specifier. When evaluated, the model elements that match the specifier are returned.

evaluate(session, models=None, *, order_implicit_atoms=False, add_implied=None, **kw)

Experimental API . Return results of evaluating atom specifier for given models.

Parameters:
  • session (chimerax.core.session.Session instance) – The session in which to evaluate atom specifier.

  • models (list of chimerax.core.models.Model instances) – Defaults to None, which uses all models in ‘session’.

  • order_implicit_atoms (whether to order atoms that aren't) – explicitly specified (e.g. “:5”) [which can be costly]

  • **kw (keyword arguments) – If ‘models’ is None, ‘kw’ is passed through to call to ‘session.models.list’ to generate the model list.

Returns:

Instance containing data (atoms, bonds, etc) that match this atom specifier.

Return type:

Objects instance

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

Bases: Annotation

Command line type annotation for atom specifiers.

See cli documentation for details on type annotations.

classmethod parse(text, session)

Experimental API . Parse text and return an atomspec parse tree

all_objects(session)

Experimental API . Return Objects that matches everything.

deregister_selector(name, logger=None)

Experimental API . Deregister a name as an atom specifier selector.

Parameters:
Raises:

KeyError – If name is not registered.

everything(session)

Experimental API . Return AtomSpec that matches everything.

Parameters:

session (instance of chimerax.core.session.Session) – Session in which the name may be used. If None, name is global.

Returns:

An AtomSpec instance that matches everything in session.

Return type:

AtomSpec instance

get_selector(name)

Experimental API . Return value associated with registered selector name.

Parameters:

name (str) – Previously registered selector name.

Returns:

Callable object if name was registered; None, if not.

Return type:

Callable object, Objects instance, or None.

get_selector_description(name, session)

Experimental API . Return description for selector.

Parameters:
  • session (instance of chimerax.core.session.Session) – Session in which the name may be used. If None, name is global.

  • name (str) – Previously registered selector name.

Returns:

Description of selector. Registered description is used when available; otherwise, description is generated from the selector value.

Return type:

string

is_selector_atomic(name)

Experimental API . Return whether selector may select any atoms.

Parameters:

name (str) – Previously registered selector name.

Returns:

Whether selector name may select any atoms.

Return type:

Boolean

is_selector_user_defined(name)

Experimental API . Return whether selector name is user-defined.

Parameters:

name (str) – Previously registered selector name.

Returns:

Whether selector name is user-defined.

Return type:

Boolean

list_selectors()

Experimental API . Return a list of all registered selector names.

Returns:

Iterator that yields registered selector names.

Return type:

iterator yielding str

register_selector(name, value, logger, *, user=False, desc=None, atomic=True)

Experimental API . Register a (name, value) pair as an atom specifier selector.

Parameters:
  • name (str) – Selector name, preferably without whitespace.

  • value (callable object or instance of Objects) – Selector value. If a callable object, called as ‘value(session, models, results)’ where ‘models’ are chimerax.core.models.Model instances and ‘results’ is an Objects instance; the callable is expected to add selected items to ‘results’. If an Objects instance, items in value are merged with already selected items.

  • logger (instance of chimerax.core.logger.Logger) – Current logger.

  • user (boolean) – Boolean value indicating whether name is considered user-defined or not.

  • desc (string) – Selector description. Returned by get_selector_description(). If not supplied, a generic description will be generated.

  • atomic (boolean) – Boolean value indicating atoms may be selected using selector. Non-atomic selectors will not appear in Basic Actions tool.

run(session, text, *, log=True, downgrade_errors=False, return_json=False, return_list=False)

Experimental API . execute a textual command

Parameters:
  • text (string) – The text of the command to execute.

  • log (bool) – Print the command text to the reply log.

  • downgrade_errors (bool) – True if errors in the command should be logged as informational.

  • return_json (bool) – If True, underlying commands that themselves support a ‘return_json’ keyword should return a JSONResult object.

  • return_list (bool) – True if a list should be returned even if only one command is executed

runscript(session, script_file, *, args=None)

Experimental API . Execute a Python or ChimeraX command script with arguments

Parameters:
  • script_file (string) – Path to Python script file

  • args (string) – Optional string containing the arguments to pass to the script