Fork me on GitHub

argparse

Build Status NPM version

CLI arguments parser for node.js. Javascript port of python's argparse module (original version 3.2). That's a full port, except some very rare options, recorded in issue tracker.

NB. Difference with original.

  • Method names changed to camelCase. See generated docs.
  • Use defaultValue instead of default.

Example

test.js file:

#!/usr/bin/env node
'use strict';

var ArgumentParser = require('../lib/argparse').ArgumentParser;
var parser = new ArgumentParser({
  version: '0.0.1',
  addHelp:true,
  description: 'Argparse example'
});
parser.addArgument(
  [ '-f', '--foo' ],
  {
    help: 'foo bar'
  }
);
parser.addArgument(
  [ '-b', '--bar' ],
  {
    help: 'bar foo'
  }
);
parser.addArgument(
  '--baz',
  {
    help: 'baz bar'
  }
);
var args = parser.parseArgs();
console.dir(args);

Display help:

$ ./test.js -h
usage: example.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ]

Argparse example

Optional arguments:
  -h, --help         Show this help message and exit.
  -v, --version      Show program's version number and exit.
  -f FOO, --foo FOO  foo bar
  -b BAR, --bar BAR  bar foo
  --baz BAZ          baz bar

Parse arguments:

$ ./test.js -f=3 --bar=4 --baz 5
{ foo: '3', bar: '4', baz: '5' }

More examples.

ArgumentParser objects

new ArgumentParser({paramters hash});

Creates a new ArgumentParser object.

Supported params:

  • description - Text to display before the argument help.
  • epilog - Text to display after the argument help.
  • addHelp - Add a -h/–help option to the parser. (default: true)
  • argumentDefault - Set the global default value for arguments. (default: null)
  • parents - A list of ArgumentParser objects whose arguments should also be included.
  • prefixChars - The set of characters that prefix optional arguments. (default: ‘-‘)
  • formatterClass - A class for customizing the help output.
  • prog - The name of the program (default: path.basename(process.argv[1]))
  • usage - The string describing the program usage (default: generated)
  • conflictHandler - Usually unnecessary, defines strategy for resolving conflicting optionals.

Not supportied yet

  • fromfilePrefixChars - The set of characters that prefix files from which additional arguments should be read.

Details in original ArgumentParser guide

addArgument() method

ArgumentParser.addArgument(name or flag or [name] or [flags...], {options})

Defines how a single command-line argument should be parsed.

  • name or flag or [name] or [flags...] - Either a positional name (e.g., 'foo'), a single option (e.g., '-f' or '--foo'), an array of a single positional name (e.g., ['foo']), or an array of options (e.g., ['-f', '--foo']).

Options:

  • action - The basic type of action to be taken when this argument is encountered at the command line.
  • nargs- The number of command-line arguments that should be consumed.
  • constant - A constant value required by some action and nargs selections.
  • defaultValue - The value produced if the argument is absent from the command line.
  • type - The type to which the command-line argument should be converted.
  • choices - A container of the allowable values for the argument.
  • required - Whether or not the command-line option may be omitted (optionals only).
  • help - A brief description of what the argument does.
  • metavar - A name for the argument in usage messages.
  • dest - The name of the attribute to be added to the object returned by parseArgs().

Details in original add_argument guide

Action (some details)

ArgumentParser objects associate command-line arguments with actions. These actions can do just about anything with the command-line arguments associated with them, though most actions simply add an attribute to the object returned by parseArgs(). The action keyword argument specifies how the command-line arguments should be handled. The supported actions are:

  • store - Just stores the argument’s value. This is the default action.
  • storeConst - Stores value, specified by the const keyword argument. (Note that the const keyword argument defaults to the rather unhelpful None.) The 'storeConst' action is most commonly used with optional arguments, that specify some sort of flag.
  • storeTrue and storeFalse - Stores values True and False respectively. These are special cases of 'storeConst'.
  • append - Stores a list, and appends each argument value to the list. This is useful to allow an option to be specified multiple times.
  • appendConst - Stores a list, and appends value, specified by the const keyword argument to the list. (Note, that the const keyword argument defaults is None.) The 'appendConst' action is typically used when multiple arguments need to store constants to the same list.
  • count - Counts the number of times a keyword argument occurs. For example, used for increasing verbosity levels.
  • help - Prints a complete help message for all the options in the current parser and then exits. By default a help action is automatically added to the parser. See ArgumentParser for details of how the output is created.
  • version - Prints version information and exit. Expects a version= keyword argument in the addArgument() call.

Details in original action guide

Sub-commands

ArgumentParser.addSubparsers()

Many programs split their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like svn checkout, svn update, and svn commit. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments. ArgumentParser supports creation of such sub-commands with addSubparsers() method. The addSubparsers() method is normally called with no arguments and returns an special action object. This object has a single method addParser(), which takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual.

Example:

sub_commands.js

#!/usr/bin/env node
'use strict';

var ArgumentParser = require('../lib/argparse').ArgumentParser;
var parser = new ArgumentParser({
  version: '0.0.1',
  addHelp:true,
  description: 'Argparse examples: sub-commands',
});

var subparsers = parser.addSubparsers({
  title:'subcommands',
  dest:"subcommand_name"
});

var bar = subparsers.addParser('c1', {addHelp:true});
bar.addArgument(
  [ '-f', '--foo' ],
  {
    action: 'store',
    help: 'foo3 bar3'
  }
);
var bar = subparsers.addParser(
  'c2',
  {aliases:['co'], addHelp:true}
);
bar.addArgument(
  [ '-b', '--bar' ],
  {
    action: 'store',
    type: 'int',
    help: 'foo3 bar3'
  }
);

var args = parser.parseArgs();
console.dir(args);

Details in original sub-commands guide

Contributors

others

License

Copyright (c) 2012 Vitaly Puzrin. Released under the MIT license. See LICENSE for details.

Action

Description

Base class for all actions Do not call in your code, use this class only for inherits your own action

Information about how to convert command line strings to Javascript objects. Action objects are used by an ArgumentParser to represent the information needed to parse a single argument from one or more strings from the command line. The keyword arguments to the Action constructor are also all attributes of Action instances.

#####Alowed keywords:

  • store
  • storeConstant
  • storeTrue
  • storeFalse
  • append
  • appendConstant
  • count
  • help
  • version

Information about action options see new Action

See also original guide

Constructor

Instance methods

Action.new

    • new Action(options)

Base class for all actions. Used only for inherits

Options:
  • optionStrings A list of command-line option strings for the action.
  • dest Attribute to hold the created object(s)
  • nargs The number of command-line arguments that should be consumed. By default, one argument will be consumed and a single value will be produced.
  • constant Default value for an action with no value.
  • defaultValue The value to be produced if the option is not specified.
  • type Cast to 'string'|'int'|'float'|'complex'|function (string). If None, 'string'.
  • choices The choices available.
  • required True if the action must always be specified at the command line.
  • help The help describing the argument.
  • metavar The name to be used for the option's argument with the help string. If None, the 'dest' value will be used as the name.
nargs supported values:
  • N (an integer) consumes N arguments (and produces a list)
  • ? consumes zero or one arguments
  • * consumes zero or more arguments (and produces a list)
  • + consumes one or more arguments (and produces a list)

Note: that the difference between the default and nargs=1 is that with the default, a single value will be produced, while with nargs=1, a list containing a single value will be produced.

Action#call

    • Action#call(parser, namespace, values, optionString)
      • Void
    • parser
      • ArgumentParser
    • current parser

    • namespace
      • Namespace
    • namespace for output data

    • values
      • Array
    • parsed values

    • optionString
      • Array
    • input option string(not parsed)

Call the action. Should be implemented in inherited classes

Example
 ActionCount.prototype.call = function (parser, namespace, values, optionString) {
   namespace.set(this.dest, (namespace[this.dest] || 0) + 1);
 };

Action#getName

    • Action#getName
      • String

Tells action name

Action#isOptional

    • Action#isOptional
      • Boolean

Return true if optional

Action#isPositional

    • Action#isPositional
      • Boolean

Return true if positional

ArgumentParser

Description

Object for parsing command line strings into js objects.

Inherited from ActionContainer

Instance properties

ArgumentParser.new

    • new ArgumentParser(options)

Create a new ArgumentParser object.

Options:
  • prog The name of the program (default: Path.basename(process.argv1))
  • usage A usage message (default: auto-generated from arguments)
  • description A description of what the program does
  • epilog Text following the argument descriptions
  • parents Parsers whose arguments should be copied into this one
  • formatterClass HelpFormatter class for printing help messages
  • prefixChars Characters that prefix optional arguments
  • fromfilePrefixChars Characters that prefix files containing additional arguments
  • argumentDefault The default value for all arguments
  • addHelp Add a -h/-help option
  • conflictHandler Specifies how to handle conflicting argument names
  • debug Enable debug mode. Argument errors throw exception in debug mode and process.exit in normal. Used for development and testing (default: false)

See also original guide

ArgumentParser#addSubparsers

See also subcommands

ArgumentParser#error

    • ArgumentParser#error(message)
      • Void
    • err
      • Error
      • string
    • message

Error method Prints a usage message incorporating the message to stderr and exits. If you override this in a subclass, it should not return -- it should either exit or throw an exception.

ArgumentParser#exit

    • ArgumentParser#exit(status = 0, message)
      • Void
    • status
      • int
    • exit status

    • message
      • string
    • message

Print message in stderr/stdout and exit program

ArgumentParser#parseArgs

    • ArgumentParser#parseArgs(args, namespace)
    • args
      • array
    • input elements

    • namespace
      • Namespace
      • Object
    • result object

Parsed args and throws error if some arguments are not recognized

See also original guide

ArgumentParser#parseKnownArgs

    • ArgumentParser#parseKnownArgs(args, namespace)
      • array
    • args
      • array
    • input options

    • namespace
      • Namespace
      • Object
    • result object

Parse known arguments and return tuple of result object and unknown args

See also original guide

ArgumentParser#printHelp

    • ArgumentParser#printHelp()
      • Void

Print help

See also original guide

ArgumentParser#printUsage

    • ArgumentParser#printUsage()
      • Void

Print usage

See also original guide

ArgumentParser#formatHelp

    • ArgumentParser#formatHelp
      • string

Return help

See also original guide

ArgumentParser#formatUsage

    • ArgumentParser#formatUsage
      • string

Return usage string

See also original guide

HelpFormatter

Description

Formatter for generating usage messages and argument help strings. Only the name of this class is considered a public API. All the methods provided by the class are considered an implementation detail.

Do not call in your code, use this class only for inherits your own forvatter

ToDo add additonal formatters

Instance properties

HelpFormatter.new

    • new HelpFormatter(options)

Options:

  • prog: program name
  • indentIncriment: indent step, default value 2
  • maxHelpPosition: max help position, default value = 24
  • width: line width

HelpFormatter#addArgument

    • HelpFormatter#addArgument(action)
      • Void
    • action
      • object
    • action

Add argument into current section

Single variant of HelpFormatter#addArguments

HelpFormatter#addArguments

    • HelpFormatter#addArguments(actions)
      • Void
    • actions
      • array
    • actions list

Mass add arguments into current section

Example
 formatter.startSection(actionGroup.title);
 formatter.addText(actionGroup.description);
 formatter.addArguments(actionGroup._groupActions);
 formatter.endSection();

HelpFormatter#addText

    • HelpFormatter#addText(text)
      • Void
    • text
      • string
    • plain text

Add plain text into current section

Example
 formatter.startSection(actionGroup.title);
 formatter.addText(actionGroup.description);
 formatter.addArguments(actionGroup._groupActions);
 formatter.endSection();

HelpFormatter#addUsage

    • HelpFormatter#addUsage(usage, actions, groups, prefix)
      • Void
    • usage
      • string
    • usage text

    • actions
      • array
    • actions list

    • groups
      • array
    • groups list

    • prefix
      • string
    • usage prefix

Add usage data into current section

Example
 formatter.addUsage(this.usage, this._actions, []);
 return formatter.formatHelp();

HelpFormatter#startSection

    • HelpFormatter#startSection(heading)
      • Void
    • heading
      • string
    • header string

Start new help section

See alse [code example][1]

Example
 formatter.startSection(actionGroup.title);
 formatter.addText(actionGroup.description);
 formatter.addArguments(actionGroup._groupActions);
 formatter.endSection();

HelpFormatter#endSection

    • HelpFormatter#endSection
      • Void

End help section

Example
 formatter.startSection(actionGroup.title);
 formatter.addText(actionGroup.description);
 formatter.addArguments(actionGroup._groupActions);
 formatter.endSection();

HelpFormatter#formatHelp

    • HelpFormatter#formatHelp
      • string

Format help

Example
 formatter.addText(this.epilog);
 return formatter.formatHelp();

Namespace

Description

Simple object for storing attributes. Implements equality by attribute names and values, and provides a simple string representation.

See also original guide

Constructor

Instance methods

Namespace.new

    • new Namespace(options)
    • options
      • object
    • predefined propertis for result object

Namespace#get

    • Namespace#get(key, defaultValue)
      • mixed
    • key
      • string
      • number
    • property name

    • defaultValue
      • mixed
    • default value

Return the property key or defaulValue if not set

Namespace#isset

    • Namespace#isset(key)
      • Boolean
    • key
      • string
      • number
    • property name

Tells whenever namespace contains given key or not.

Namespace#set

    • Namespace#set(key, value)
      • self
    • key
      • string
      • number
      • object
    • propery name

    • value
      • mixed
    • new property value

Set the property named key with value. If key object then set all key properties to namespace object

Namespace#unset

    • Namespace#unset(key, defaultValue)
      • mixed
    • key
      • string
      • number
    • property name

    • defaultValue
      • mixed
    • default value

Return data[key](and delete it) or defaultValue