schrodinger.utils.cmdline module

Functions and classes to assist in standard processing of command line arguments.

The preferred way to use this module is by the SingleDashOptionParser class, which subclasses the standard library’s optparse.OptionParser. The SingleDashOptionParser class provides the standard -h and -v options and finds the script by parsing the ‘version_source’ argument provided to the constructor. Example usage:

parser = SingleDashOptionParser(usage="%prog [<options>] <mae file>"
        version_source=__doc__)
parser.add_option("-d", "-debug", action="store_true",
        default=False,
        dest="debug",
        help="print extra debugging output")
options, args = parser.parse_args()

Command Line Guidelines

Form of Options

Long Options

Long options should use single-dash, not double dash. That is, use -verbose, not –verbose. (Note that this means that clustering of short options is not available. It also means that spaces are required between short options and values - i.e. -lquiet is not equivalent to -l quiet as it is in the default OptionParser.) Long options should not be all upper case, as that is reserved for job control options.

Boolean Options

For boolean options, prefer either -log vs <nothing> or -log vs. -nolog to anything that requires the specification of some true/false value to the option.

Usage messages

Usage messages should be explicitly defined when using the SingleDashOptionParser.

Form

Script usage statements should follow the style outlined in our printed documentation. Arguments are typically listed after options in the usage message. Whenever possible, the message should list all script options. Below is a glossary of markup symbols and examples:

  • <> Angle brackets denote a place where the user should provide a value, as opposed to typing the literal string in the usage statement. The contents of the <> braces appear as italic text in the printed documentation.
  • [] Square braces denote optional user input.
  • | A vertical bar separates mutually exclusive options in either square or curly brackets.
  • Ellipsis denote optional, repeated arguments of the same type.
  • {} Curly braces denote ‘required options’. Required options should be avoided. When a script can operate in multiple modes, please choose one as the default rather than requiring an option to be specified by the user with every invocation.

Examples

  1. Usage: $SCHRODINGER/run cmdline_ex.py <file> ...

    <file> represents a variable file name provided the user, means that the script allows, but does not require, subsequent file name arguments.

  2. Usage: $SCHRODINGER/run cmdline_ex.py [-color blue|red] <file>

    [-color blue|red] means that the -color flag is optional, and when present it needs one of two string literals, either blue or red. Note: the -color flag is not required and is truly “optional”, the script does something useful without the -color switch modifier.

  3. Usage: $SCHRODINGER/run cmdline_ex.py [-host localhost|<ip_address>] <file>

    -host is an option that modifies the default behavior. -host consumes either the string literal localhost or a user-supplied IP address.

Copyright Schrodinger, LLC. All rights reserved.

schrodinger.utils.cmdline.main_wrapper(main, *args, **kwargs)

Wrap ‘main’ functions for improved user interaction.

This function will call the provided ‘main’ function while installing an exception handler that saves tracebacks to a file (unless running in a development environment). KeyboardInterrupt and BrokenPipeError exceptions are handled silently and simply exit with code 1.

Parameters:
  • main (callable) – The function that should be called.
  • args – Additional positional arguments will be passed to the provided main function when it is called.
schrodinger.utils.cmdline.print_version(version_source='')

Print the script version and exit.

Parameters:version_source (str) – The string to search for a Revision tag.
schrodinger.utils.cmdline.version_string(version_source='')

Form a standard version string from a source string. The source string is searched for an embedded CVS Revision tag. If one is found, that is used as the script version. If no Revision tag is found, only Schrodinger python version information is included.

schrodinger.utils.cmdline.add_jobcontrol_options(parser, options=None, group_options=True)

Adds common Job Control options to a SingleDashOptionParser or argparse.ArgumentParser instance.

The options are specified as a list of module enums. Note that HOSTLIST option is deprecated. Use HOST option instead.

Note that HOST, TMPDIR and SAVE are ‘top-level’ options and are not passed down from the top-level script (i.e. $SCHRODINGER/run). These are available so the options appear in the command line help. There are functions in schrodinger.job.jobcontrol that get HOST information, and environment variables can be queried for TMPDIR and SAVE if needed.

Example usage:

parser = cmdline.SingleDashOptionParser()
cmdline.add_jobcontrol_options(parser)
(opts, args) = parser.parse_args()
if opts.wait:
   # Provide wait argument to launch invocation.
if opts.local:
   # Use the cwd as the jobdir.
Parameters:
  • parser (SingleDashOptionParser or ArgumentParser) – Instance of this module’s SingleDashOptionParser or instance of argparse.ArgumentParser.
  • options (list) – List of module enums that indicate what options to add to the parser.
  • group_options (bool) – If True then group the added options (via an optparse.OptionGroup) in the help message under the header ‘Job Control Options’.
schrodinger.utils.cmdline.add_standard_options(parser, options=None, group_options=True, default_retries=None)

Adds standard options to a SingleDashOptionParser or argparse.ArgumentParser instance.

The options are specified as a list of module enums. Accepted values are NJOBS, NSTRUCTS, STRICT, RETRIES, NOLAUNCH, and RESTART.

Please note that NJOBS and NSTRUCTS options are mutual exclusive. i.e. njobs = total_structures / structures_per_job

User can either provide njobs or structures_per_job; so one option is affecting the other option (in short, in specifying one option it can set the proper value for the other option), hence NJOBS and NSTRUCTS options are mutual exclusive.

Example usage:

parser = cmdline.SingleDashOptionParser()
cmdline.add_standard_options(parser)
(opts, args) = cmdline.parse_standard_options(parser, args)
if opts.njobs:
   # Provide njob argument to launch invocation.
Parameters:
  • parser (SingleDashOptionParser or ArgumentParser) – Instance of this module’s SingleDashOptionParser or insance of argparseArgumentParser.
  • options (list) – List of module enums that indicate what options to add to the parser.
  • group_options – If True then group the added options (via an optparse.OptionGroup) in the help message under the header ‘Standard Options’.
  • group_options – bool
  • default_retries – The default number of retries to use (only applies is RETRIES is included in options)
  • default_retries – integer
schrodinger.utils.cmdline.add_jobcontrol_diagnostic_options(parser, options=None, group_options=True)

Appends Job Control diagnostic options to SingleDashOptionParser or argparse.ArgumentParser instance.

These options are added simply to improve documentation uniformity to python script command line interfaces. The top-level layer should report then exit without running the script. Thus, the application script can’t act upon any of these flags.

Parameters:
  • parser (SingleDashOptionParser or ArgumentParser) – Instance of this module’s SingleDashOptionParser or instance of argparse.ArgumentParser.
  • options (list) – List of module enums that indicate what options to add to the parser.
  • group_options – If True then group the added options (via an optparse.OptionGroup) in the help message under the header ‘Diagnostic Options (Provide information but the program will not run)’.
  • group_options – Boolean
class schrodinger.utils.cmdline.SingleDashOption(*args, **kwargs)

Bases: optparse.Option

A class to automatically translate long options with single dashes into double dash long options, but still print out help with the single dash.

__init__(*args, **kwargs)

Initialize self. See help(type(self)) for accurate signature.

process_option_strings(formatted_option_strings)

Post-process the provided formatted options string to replace the translated double dash options with their original single dash specifications.

ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count', 'callback', 'help', 'version')
ALWAYS_TYPED_ACTIONS = ('store', 'append')
ATTRS = ['action', 'type', 'dest', 'default', 'nargs', 'const', 'choices', 'callback', 'callback_args', 'callback_kwargs', 'help', 'metavar']
CHECK_METHODS = [<function Option._check_action>, <function Option._check_type>, <function Option._check_choice>, <function Option._check_dest>, <function Option._check_const>, <function Option._check_nargs>, <function Option._check_callback>]
CONST_ACTIONS = ('store_const', 'append_const')
STORE_ACTIONS = ('store', 'store_const', 'store_true', 'store_false', 'append', 'append_const', 'count')
TYPED_ACTIONS = ('store', 'append', 'callback')
TYPES = ('string', 'int', 'long', 'float', 'complex', 'choice')
TYPE_CHECKER = {'choice': <function check_choice>, 'complex': <function check_builtin>, 'float': <function check_builtin>, 'int': <function check_builtin>, 'long': <function check_builtin>}
check_value(opt, value)
convert_value(opt, value)
get_opt_string()
process(opt, value, values, parser)
take_action(action, dest, opt, value, values, parser)
takes_value()
class schrodinger.utils.cmdline.DelegatingIndentedHelpFormatter(indent_increment=2, max_help_position=24, width=None, short_first=1)

Bases: optparse.IndentedHelpFormatter

An IndentedHelpFormatter class that allows an Option class to alter its own option string if it has a process_option_strings method.

format_option_strings(option)

Return a formatted option string.

Allow the provided option to alter the string if it has a process_option_strings() method.

NO_DEFAULT_VALUE = 'none'
__init__(indent_increment=2, max_help_position=24, width=None, short_first=1)

Initialize self. See help(type(self)) for accurate signature.

dedent()
expand_default(option)
format_description(description)
format_epilog(epilog)
format_heading(heading)
format_option(option)
format_usage(usage)
indent()
set_long_opt_delimiter(delim)
set_parser(parser)
set_short_opt_delimiter(delim)
store_option_strings(parser)
class schrodinger.utils.cmdline.SingleDashOptionParser(*args, **kwargs)

Bases: optparse.OptionParser

An OptionParser subclass that allows long options with a single dash.

Note that this class can therefore not be used for clustering short options - i.e. “-rf” will be interpreted as a long option “rf”, not the short options “-r” and “-f”.

__init__(*args, **kwargs)

This constructor takes the same options as the standard library’s optparse.OptionParser.

It also takes the keyword argument ‘version_source’, which should be a string containing a CVS Revision string like $Revision: 1.26 $. The ‘version_source’ argument is used to create a standard version string that also notes the Schrodinger python version number, so its use should be preferred to specifying a ‘version’ explicitly.

parse_args(args=None, values=None, ignore_unknown=False)
parse_args(args : [string] = sys.argv[1:],
values : Values = None)

-> (values : Values, args : [string])

Parse the command-line options found in ‘args’ (default: sys.argv[1:]). Any errors result in a call to ‘error()’, which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where ‘values’ is a Values instance (with all your option values) and ‘args’ is the list of arguments left over after parsing options.

has_option(option)
get_option(opt_str)

Return the Option instance with the option string opt_str, or None if no options have that string.

remove_option(opt_str)

Remove the Option with the option string opt_str.

print_usage(file : file = stdout)

Print the usage message for the current program (self.usage) to ‘file’ (default stdout). Any occurence of the string “%prog” in self.usage is replaced with the name of the current program (basename of sys.argv[0]). Does nothing if self.usage is empty or not defined.

add_option(Option)

add_option(opt_str, …, kwarg=val, …)

add_option_group(*args, **kwargs)
add_options(option_list)
check_values(values : Values, args : [string])

-> (values : Values, args : [string])

Check that the supplied option values and leftover arguments are valid. Returns the option values and leftover arguments (possibly adjusted, possibly completely new – whatever you like). Default implementation just returns the passed-in values; subclasses may override as desired.

destroy()

Declare that you are done with this OptionParser. This cleans up reference cycles so the OptionParser (and all objects referenced by it) can be garbage-collected promptly. After calling destroy(), the OptionParser is unusable.

disable_interspersed_args()

Set parsing to stop on the first non-option. Use this if you have a command processor which runs another command that has options of its own and you want to make sure these options don’t get confused.

enable_interspersed_args()

Set parsing to not stop on the first non-option, allowing interspersing switches with command arguments. This is the default behavior. See also disable_interspersed_args() and the class documentation description of the attribute allow_interspersed_args.

error(msg : string)

Print a usage message incorporating ‘msg’ to stderr and exit. If you override this in a subclass, it should not return – it should either exit or raise an exception.

exit(status=0, msg=None)
expand_prog_name(s)
format_description(formatter)
format_epilog(formatter)
format_help(formatter=None)
format_option_help(formatter=None)
get_default_values()
get_description()
get_option_group(opt_str)
get_prog_name()
get_usage()
get_version()
print_help(file : file = stdout)

Print an extended help message, listing all options and any help text provided with them, to ‘file’ (default stdout).

print_version(file : file = stdout)

Print the version message for this program (self.version) to ‘file’ (default stdout). As with print_usage(), any occurrence of “%prog” in self.version is replaced by the current program’s name. Does nothing if self.version is empty or undefined.

set_conflict_handler(handler)
set_default(dest, value)
set_defaults(**kwargs)
set_description(description)
set_process_default_values(process)
set_usage(usage)
standard_option_list = []
schrodinger.utils.cmdline.create_argument_parser(*args, **kwargs)

Factory function to get an argparse.ArgumentParser with standard help and version added in a single dash fashion.

Takes the same arguments as argparse.ArgumentParser.

Parameters:version_source (unicode) – A string containing a CVS Revision string like $Revision: 1.26 $. If not specified, it uses the Schrodinger python version number.