argparser module

Command-line argument parser (argparse extension) that adds an option repository.

Module author: Michael S. Chapman <chapmanms@missouri.edu>

Authors:

Michael S. Chapman <chapmanms@missouri.edu>

Oregon Health & Science University & University of Missouri

Version:

1, Nov 26, 2024

Main programs should import this module, subclass ArgumentParser to add support for arguments defined by the main program and/or imported modules, then call parse_args(). The default behavior of parse_args() is changed to use module global option as the repository into which argument values are put as attributes. If this module is imported into other modules, the sharing of option values is supported.

Changed in version 0.1.0: 8/13/10 Started.

Changed in version 0.3.9: 05/04/13 - converted from optparse to argparse.

Changed in version 1.0.0: 09/27/20 Python 2.7 –> 3.6, minimal changes

Changed in version 1.0.0a: 11/21/20 refactored for module options to be provided with Arguments sub-classes instead of ArgumentParser sub-classes.

Changed in version 1.0.5: 06/21/24 compatability with cmd2 2.0 breaking changes, relative imports and single package entry point.

class argparser.ArgumentParser(main=True, dot_file=True, verbose=True, *args, **kwargs)

Bases: ArgumentParser

Local extensions to argparse used by multiple programs.

No longer should be subclassed to add program-specific command-line options; instead copy the template Arguments() into the module. (With changes in python3, the prior subclassing of ArgumentParser correctly processed arguments, but only documented those in __main__ with –help.)

“+<file>” will read options from <file>, one option per line.

..error:: (from argparse.ArgumentParser?) - on ‘help’, mutually exclusive

groups from sub-parsers included in parents are listed as general options and not within the group within which they are defined. Individual sub-parser.print_help() groups correctly.

Parameters:
  • main (bool) – Parser for main program (not for imported module). Adds default program information.

  • dot_file (bool) – insert commands from ./prog.arg or ~/.prog.arg if present, one per line.

  • verbose (bool) – echo command line (if stdout is not a terminal).

dotfile()

Reads command-line-like options from .$PROGNAME.arg in $CWD or $HOME.

finalize()

Completion of the parser after program sub-class initialized.

parse_args(*args, **kwargs)

Parse options on command line (or str args), defaulting namespace to option.

Parameters:

namespace – destination of argument-derived attributes.

Returns:

object containing argument-derived attributes, saved into global option if defined, else into a new argparse.Namespace.

Return type:

argparse.Namespace or user-defined

Changed in version ?: uses __main__.option as default-only namespace if available, else continues to argparse default.

Changed in version ?: now always returns the namespace (never None).

static remaining(namespace)

Remaining tokens reparsed (protecting quoted, bracketed white-space).

Needed for compatibility between cmd2 (which supports trailing commands on command line) with argparse, which tokenizes without regard to the quotes that cmd2 uses for multi-word commands.

After completing argparse, might want to continue program execution with the unused arguments with the following: sys.argv = [sys.argv[0],] + Arguments.remaining(option)

Parameters:

namespace (obj) – where argparse has put assigned variables.

Returns:

reparsed unused tokens

Return type:

list

class argparser.Arguments(imports=[], main=None, *args, **kwargs)

Bases: ArgumentParser

Manager for command-line arguments from main and imported modules.

Changed in version 1.0.0a: This should now be sub-classed to expose an imported module’s command-line options.

See also

ArgumentsSubClass provides a template subclass to be copied into modules and edited.

Parameters:
  • imports ((list of) ArgumentParser(s)) – (list of) module(s) from which to obtain “parent” ArgumentParser objects for inclusion.

  • main (bool|NoneType) – Add information and arguments appropriate for a main program (or not); if None, will determine by whether this class is defined in __main__.

domestic()

Defines options used only when main program and not when imported.

export()

Defines options used in both stand-alone and imported modes.

class argparser.ArgumentsSubClass(imports=[], main=None, *args, **kwargs)

Bases: Arguments

Manager for command-line arguments from main and imported modules.

This is a template to be copied into modules, for the handling of command- line options, and would appear something like: class Arguments(argparser.Arguments).

methods export(), domestic() & (optionally) finalize() should be overridden by the module subclass with declarations of the command-line arguments needed by the module.

Parameters:
  • imports ((list of) ArgumentParser(s)) – (list of) module(s) from which to obtain “parent” ArgumentParser objects for inclusion.

  • main (bool|NoneType) – Add information and arguments appropriate for a main program (or not); if None, will determine by whether this class is defined in __main__.

domestic()

Defines options used only when main program and not when imported.

This method should only be called from a __main__ program, and should instantiate an argparser.ArgumentParser object and populate it with the arguments available (only) when used as a main program. Code after the “pass” can optionally be deleted if never used as a main program.

export()

Defines options used in both stand-alone and imported modes.

Code after the “pass” should be replaced by ArgumentParser directives specific for the module, or deleted & left blank if none.

class argparser.CommonOptions

Bases: object

Maintains object option whose attributes are program options.

Should be sub-classed for program-specific options.

asdict()

Dictionary of options, values.

Excludes private attributes, methods and class instances.

Returns:

option key and value pairs.

Return type:

dictionary

class argparser.Namespace(**kwargs)

Bases: Namespace

asdict()

Dictionary of the arguments without the Namespace metadata.

Returns:

arguments

Return type:

dict

class argparser.Options

Bases: CommonOptions

Repository for all user-controllable parameters.

Minimalist class into which argparser and importing modules will place attributes and properties related to command-line arguments. (option needs to be instantiated before dependent modules are imported.)

argparser.protectedSplit(text, separator=None)

Divide into words w/ separator not protected by quotes, brackets.

Parameters:
  • text (str) – to be parsed

  • separator (str) – token separator, if None - any whitespace.

argparser.quoted(text)
argparser.token(text, separator=None)

1st token before a separator not protected by quotes, brackets.

Parameters:
  • text (str) – to be parsed

  • separator (str) – token separator, if None - any whitespace.