What is argparse?
The argparse npm package is a node.js module for parsing command-line options and arguments. It is inspired by the Python argparse module and allows developers to create user-friendly command-line interfaces for their applications. It provides a way to specify what arguments the program requires, and parses those arguments from the process.argv array.
What are argparse's main functionalities?
Argument Parsing
This feature allows the program to parse command-line arguments. The code sample demonstrates how to create a new ArgumentParser, add arguments with options like verbosity, and then parse the arguments provided by the user.
const { ArgumentParser } = require('argparse');
const parser = new ArgumentParser({
description: 'Argparse example'
});
parser.add_argument('-v', '--verbose', {
help: 'increase output verbosity',
action: 'store_true'
});
parser.add_argument('echo', {
help: 'echo the string you use here'
});
const args = parser.parse_args();
console.log(args);
Sub-commands
This feature allows the program to define sub-commands, which are commands that the program can perform. The code sample shows how to create sub-commands for starting and stopping a service, with additional options for each sub-command.
const { ArgumentParser } = require('argparse');
const parser = new ArgumentParser({
description: 'Sub-command example'
});
const subparsers = parser.add_subparsers({
title: 'subcommands',
dest: 'subcommand_name'
});
const start = subparsers.add_parser('start', { aliases: ['run'] });
start.add_argument('-s', '--service', { help: 'Start the service' });
const stop = subparsers.add_parser('stop');
stop.add_argument('-f', '--force', { help: 'Force stop', action: 'store_true' });
const args = parser.parse_args();
console.log(args);
Argument Types and Choices
This feature allows the program to specify the type of an argument and restrict it to a set of choices. The code sample demonstrates how to define an integer argument and a string argument that must be one of the specified choices.
const { ArgumentParser } = require('argparse');
const parser = new ArgumentParser({
description: 'Argument types example'
});
parser.add_argument('square', {
help: 'display a square of a given number',
type: 'int'
});
parser.add_argument('--cuisine', {
help: 'choose the type of cuisine',
choices: ['Italian', 'Mexican', 'Japanese'],
required: true
});
const args = parser.parse_args();
console.log(args);
Other packages similar to argparse
commander
Commander is another popular npm package for command-line interfaces. It provides a high-level way to specify commands and options, and it automatically generates help messages. Commander is known for its simplicity and declarative style of defining command-line options.
yargs
Yargs is a node.js library that helps build interactive command-line tools, by parsing arguments and generating an elegant user interface. It comes with features like command chaining, automatic help generation, and more. Yargs is often praised for its fluent API and its support for advanced features like command-specific configurations.
minimist
Minimist is a minimalistic argument parsing library. It is designed to be simple and straightforward, with fewer features than argparse, commander, or yargs. It is a good choice for those who need something lightweight without the need for complex command-line interfaces.
argparse
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. Method names changed to camelCase. See generated docs.
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'
}
);
var args = parser.parseArgs();
console.dir(args);
Display help:
$ ./test.js -h
usage: example.js [-h] [-v] [-f FOO] [-b BAR]
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
Parse arguments:
$ ./test.js -f=3 --bar=4
{ foo: '3', bar: '4' }
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: None)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: sys.argv[0])usage
- The string describing the program usage (default: generated)
Not supportied yet
fromfilePrefixChars
- The set of characters that prefix files from which additional arguments should be read.conflictHandler
- Usually unnecessary, defines strategy for resolving conflicting optionals.
Details in original ArgumentParser guide
addArgument() method
ArgumentParser.addArgument([names or flags], {options})
Defines how a single command-line argument should be parsed.
name or flags
- Either a name or a list of option strings, e.g. foo or -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
Author
Eugene Shkuropat
License
Copyright (c) 2012 Vitaly Puzrin.
Released under the MIT license. See
LICENSE for details.