Wolfram Language Paclet Repository

Community-contributed installable additions to the Wolfram Language

Primary Navigation

    • Cloud & Deployment
    • Core Language & Structure
    • Data Manipulation & Analysis
    • Engineering Data & Computation
    • External Interfaces & Connections
    • Financial Data & Computation
    • Geographic Data & Computation
    • Geometry
    • Graphs & Networks
    • Higher Mathematical Computation
    • Images
    • Knowledge Representation & Natural Language
    • Machine Learning
    • Notebook Documents & Presentation
    • Scientific and Medical Data & Computation
    • Social, Cultural & Linguistic Data
    • Strings & Text
    • Symbolic & Numeric Computation
    • System Operation & Setup
    • Time-Related Computation
    • User Interface Construction
    • Visualization & Graphics
    • Random Paclet
    • Alphabetical List
  • Using Paclets
    • Get Started
    • Download Definition Notebook
  • Learn More about Wolfram Language

CommandLineParser

Tech Notes

  • CommandLineParser Documentation
CommandLineParser Documentation
Introduction
Argument specifications
Specification & usage basics
Variadic arguments
Introduction
CommandLineParser is meant to be used from Wolfram Language scripts. Such scripts should first load CommandLineParser, then specify their arguments and then run ParseCommandLine:
(* script.m *)
Needs["Wolfram`CommandLineParser`"];
spec = ...;
parsedArgs = ParseCommandLine[spec];
The 1-argument form ParseCommandLine[spec] automatically grabs the list of arguments provided to the script (using $CommandLine or $ScriptCommandLine). In this documentation we will instead use the 2-argument form which explicitly requires the argument list to be provided, e.g.:
In[104]:=
spec={{"my-int-arg"NumericSpec["Integer","An unbounded integer"]},{}};​​ParseCommandLine[spec,{"42"}]
Out[105]=
{my-int-arg42,}
Specification & usage basics
ParseCommandLine usually returns a list of the form {parsedPosArgs, parsedOpts} where parsedPosArgs and parsedOpts are both associations containing the names and parsed values of positional and optional arguments respectively. The association parsedOpts contains all the option values, including those not specified by the user.
In ParseCommandLine[spec] argument spec has the form {posArgSpecs,optArgSpecs,helpHeader} or just {posArgSpecs,optArgSpecs}:
◼
  • posArgSpecs is a list defining the specification for positional arguments which should be provided in the same order from the command line. It has the form {argName -> argSpec, ...}, where argName is a string. Default values can be specified by using {argName, default} -> argSpec instead, where default is a string . Positional arguments without defaults cannot appear after positional arguments with defaults.
  • ◼
  • optArgSpecs is a list defining the specification for optional arguments. It usually has the form {{argName, default} -> argSpec, ...}, where argName and default are both strings. default is the option default which is mandatory (unless the optional argument is variadic, more on this in the following sections).
  • ◼
  • helpHeader is used for documentation purposes.
  • An example for a full specification is:
    In[3]:=
    posArgSpecs={​​"my-string-arg"StringSpec["A generic string argument"],​​"my-symbol-arg"EnumSpec[{None,Automatic,Inherited},"A special symbol. Can be None, Automatic, Inherited or their lower-case equivalents"],{"my-numeric-arg","7"}NumericSpec["Integer","Any sequence of positive integers, including none"]​​};
    In[4]:=
    optArgSpecs={​​{"my-numeric-opt","0.5"}NumericSpec["Real","A real number between 0 and 1","Interval"{0,1}],​​{"my-boolean-opt","false"}BooleanSpec["A boolean"]​​};
    In[5]:=
    helpHeader="Welcome to my script!";
    In[6]:=
    spec={posArgSpecs,optArgSpecs,helpHeader};
    When providing user input, positional argument should appear in the correct order followed by the desired optional settings. Optional arguments are passed as --opt-name=...:
    In[7]:=
    ParseCommandLine[spec,{"hello","none","5","--my-numeric-opt=0.41"}]
    Out[7]=
    {my-string-arghello,my-symbol-argNone,my-numeric-arg5,my-numeric-opt0.41,my-boolean-optFalse}
    If the above code was used in a script called MyScript.m, the command line call equivalent of the above example would be e.g.:
    math -script MyScript.m hello none 5 --my-numeric-opt=0.41
    Positional arguments with defaults ("my-numeric-arg") can be omitted:
    In[280]:=
    ParseCommandLine[spec,{"hello","none","--my-numeric-opt=0.41"}]
    Out[280]=
    {my-string-arghello,my-symbol-argNone,my-numeric-arg7,my-numeric-opt0.41,my-boolean-optFalse}
    For optional arguments --opt-name is interpreted as --opt-name=True.
    In[281]:=
    ParseCommandLine[spec,{"hello","none","--my-boolean-opt"}]
    Out[281]=
    {my-string-arghello,my-symbol-argNone,my-numeric-arg7,my-numeric-opt0.5,my-boolean-optTrue}
    If the list of arguments contains --help in any position, an auto-generated help message is printed. The message uses the information provided in the argument specs to document all available arguments and options. helpHeader is prepended to the message if present:
    In[282]:=
    ParseCommandLine[spec,{"--help"}]
    Welcome to my script!
    * Mandatory positional arguments:
    NAME DOCUMENTATION
    my-string-arg A generic string argument
    my-symbol-arg A special symbol. Can be None, Automatic, Inherited or their lower-case equivalents
    * Optional positional arguments (must be passed in this order after the mandatory arguments):
    NAME DEFAULT DOCUMENTATION
    my-numeric-arg 7 Any sequence of positive integers, including none
    * Optional arguments (must be passed as --name=... in any order):
    NAME DEFAULT DOCUMENTATION
    my-numeric-opt 0.5 A real number between 0 and 1
    my-boolean-opt false A boolean
    Out[282]=
    $Aborted
    If a parsing error occurs, ParseCommandLine will output an informative message and call Abort[] in order to immediately exit the script:
    In[283]:=
    ParseCommandLine[spec,{"hello","badValue"}]
    ParseCommandLine
    ::nomatch
    :Positional argument my-symbol-arg (position 2) was badValue​, which is an invalid value. Documentation string for the argument is: A special symbol. Can be None, Automatic, Inherited or their lower-case equivalents.
    ​
    Out[283]=
    $Aborted
    The call to Abort[] can be avoided by setting the option "ReturnOnError" -> True, in which case ParseCommandLine will return $Failed and the script execution will continue:
    In[285]:=
    ParseCommandLine[spec,{"hello","badValue"},"ReturnOnError"True]
    ParseCommandLine
    ::nomatch
    :Positional argument my-symbol-arg (position 2) was badValue​, which is an invalid value. Documentation string for the argument is: A special symbol. Can be None, Automatic, Inherited or their lower-case equivalents.
    ​
    Out[285]=
    $Failed
    Similarly, Abort[] will also be called when the help message is printed, which can be prevented by setting "ReturnOnHelp" -> True. In this case ParseCommandLine will return Null.
    In[287]:=
    ParseCommandLine[spec,{"--help"},"ReturnOnHelp"True]
    Welcome to my script!
    * Mandatory positional arguments:
    NAME DOCUMENTATION
    my-string-arg A generic string argument
    my-symbol-arg A special symbol. Can be None, Automatic, Inherited or their lower-case equivalents
    * Optional positional arguments (must be passed in this order after the mandatory arguments):
    NAME DEFAULT DOCUMENTATION
    my-numeric-arg 7 Any sequence of positive integers, including none
    * Optional arguments (must be passed as --name=... in any order):
    NAME DEFAULT DOCUMENTATION
    my-numeric-opt 0.5 A real number between 0 and 1
    my-boolean-opt false A boolean
    Argument specifications
    There are two ways of defining arguments for ParseCommandLine: a low-level specification format and a set of high-level helpers to generate said low-level specifications for common use cases (numeric arguments, boolean arguments, ...).

    Low-level argument specification

    The low-level argument specification is a list of the form {stringPatt,parser,postCheck, variadic,docString}:
    ◼
  • stringPatt is a string pattern that validates the input string from the command line. The input string must
    StringMatchQ
    with stringPatt, otherwise an error is generated.
  • ◼
  • parser is a
    Function
    object that is applied to the input string (after string pattern validation) and produces the desired final expression.
  • ◼
  • postCheck is a
    Function
    object that is applied to the output of parser and can check its value. It should return
    True
    in case the check is successful, otherwise an error is generated.
  • ◼
  • variadic is a boolean that specifies if the given argument is variadic (more on this in the following sections)
  • ◼
  • docString is a documentation string for the argument and its allowed values. It is shown in parsing error messages and in the auto-generated help message (--help).
  • Here is an example of a low level argument specification. It accepts a number string or the string "pi", the parser converts the input string to a number and the checker constrains the parsed value to be less than 10. The parser and checker produce a print when they are ran:
    In[288]:=
    stringPatt=NumberString|"pi";​​parser=Function[​​Print["Running parser"];​​Replace[#,{"pi"Pi,n_ToExpression[n]}]​​];​​postCheck=Function[​​Print["Running check"];​​#<10​​];​​variadic=False;​​docString="Either a number less than 10 or pi";
    In[293]:=
    lowLevelArgSpec={stringPatt,parser,postCheck,variadic,docString};
    The above argument specification can be used to build a full parser specification for a command line interface that takes a single positional argument:
    In[294]:=
    parserSpec={{"my-arg"lowLevelArgSpec},{}};
    In[295]:=
    ParseCommandLine[parserSpec,{"2.3"}]
    Running parser
    Running check
    Out[295]=
    {my-arg2.3,}

    High-level argument helpers

    The high level helpers are simple functions which output low level argument specifications for the most common use cases. An example is:
    As shown in the above example, low-level specifications produced by the helpers can become verbose, but the developer doesn't have to interact with them directly.
    StringSpec[docString] generates a specification for a string that is taken verbatim from the command line. No transformation or check is performed.
    ◼
  • docString is the documentation string for the argument
  • ◼
  • Can set the option "Variadic" -> True to make it variadic (more on this in the following sections)
  • ◼
  • docString is the documentation string for the argument
  • ◼
  • Can set the option "Variadic" -> True to make it variadic (more on this in the following sections)
  • NumericSpec[type, docString] generates a specification for a number. The value returned by the parser is either a number, Infinity or -Infinity (more precisely, DirectedInfinity[1] and DirectedInfinity[-1] respectively).
    ◼
  • type is either "Real" or "Integer"
  • ◼
  • docString is the documentation string for the argument
  • ◼
  • Can set the option "Interval" -> {a, b} to specify an allowed interval (endpoints allowed). Can use Infinity for unbounded intervals
  • ◼
  • Can set the option "AllowInfinity" -> True to actually allow Infinity or -Infinity as input values (or their lower-cased equivalents). They will be parsed to their equivalent symbolic expressions
  • ◼
  • Can set the option "Variadic" -> True to make it variadic (more on this in the following sections)
  • ◼
  • values is the list of desired values. Both symbols and strings can be used
  • ◼
  • docString is the documentation string for the argument
  • ◼
  • Can set the option "Variadic" -> True to make it variadic (more on this in the following sections)
  • RepeatedSpec[singleSpec, separator, docString] generates a specification for a list of values each specified by singleSpec. Values must be separated using separator with no spaces, and the elements are collected into a list. It is possible to create an empty list by just passing separator as the argument value, or by --opt-name= for optional arguments.
    ◼
  • singleSpec is the specification for the individual elements. It can be an explicit low-level specification or it can be generated by other high-level helpers. Each of the provided elements are parsed individually according to singleSpec
  • ◼
  • separator is a string of one or more characters used to separate individual values. It cannot be a whitespace
  • ◼
  • docString is the documentation string for the argument. The documentation string of singleSpec is ignored
  • Variadic arguments
    Variadic argument specifications have True as the 4th element of their low-level specification. This feature fundamentally changes how arguments are treated by the parser. Any number of optional arguments can be variadic but only one positional argument can, and it must appear as the very last element in the specification (after all positional arguments without default and all positional arguments with default). For variadic arguments, ParseCommandLine always returns a list of the objects produced by their parser.
    A positional variadic argument is passed from the command line as a sequence of values like val1 val2 val3. Optional variadic arguments require the option name to be repeated for every element as in --opt-name=val1 --opt-name=val2 --opt-name=val3. In both cases ParseCommandLine will return the list of objects resulting from mapping the parser on {val1, val2, val3}.
    In case nothing is passed to either the positional or optional arguments an empty list will be returned:
    Thus it follows that variadic arguments cannot have defaults: a specification of the form {name, default} -> spec will be rejected if spec is variadic:
    Variadic arguments and non-variadic arguments produced by the high-level helper RepeatedSpec are two different ways to parse lists of arguments, each with its own pros and cons. Only one positional argument can be variadic but any number of arguments can by defined by RepeatedSpec, and variadic optional arguments are cumbersome to specify because the argument name has to be repeated for each element. But variadic arguments don't have to rely on a separator character so they are more general (single values to be parsed cannot contain the separator with RepeatedSpec).

    © 2025 Wolfram. All rights reserved.

    • Legal & Privacy Policy
    • Contact Us
    • WolframAlpha.com
    • WolframCloud.com