Function Repository Resource:

CommandLineTools

Source Notebook

A collection of command line tools and utilities, streamlining wolframscript creation

Contributed by: Antonis Aristeidou

ResourceFunction["CommandLineTools"]["Parse"]

parses the command line creating an association of flag-argument pairs.

ResourceFunction["CommandLineTools"]["Parse",form]

parses the command line and returns flag-argument pairs where the flag matches form.

ResourceFunction["CommandLineTools"]["FlagQ",form]

returns True or False if flag matching form is passd to the command line.

ResourceFunction["CommandLineTools"]["Interface"]

creates a blocking interface with default commands.

ResourceFunction["CommandLineTools"]["Interface",cmds]

creates a blocking interface with additional custom commands cmds.

ResourceFunction["CommandLineTools"]["Log",lvl,msg]

logs msg to stdout and to a file at log level lvl.

ResourceFunction["CommandLineTools"]["Log",lvl]

is an operator form of Log method.

ResourceFunction["CommandLineTools"]["Help"]

prints a help message to stdout.

Details and Options

lvl for for "Log" can be: "INFO", "WARN", "ERROR", "SUCCESS".
ResourceFunction["CommandLineTools"] had the following options and settings:
"CommandLine"AutomaticCommand line to parse
"POSIX"FalseRestrict to the POSIX convention for short and long options
"InterfacePrompt""wls-cli>"Interface input prompt
"InterfaceCommands"defaultCommandsDelayed rules corresponding to the defined interface commands
"OptionDelimiter"" " | "="Option delimiter form
"ArgumentDelimiter"","Argument delimiter form
"HelpMessage""CommandLineTools example interface"Help message
"LogToFile"TrueWhether "Log" should log to a file
"LogToStdOut"TrueWhether "Log" should log to stdout
"LogDirectory""./logs/wls-cli"Directory log files should be placed in
"ArgumentSpecification"NoneOption and argument pattern specification
"StrictParse"FalseReturn failure if unknown option is passed
cmds and "InterfaceCommands " for the "Interface" method is a List or Association of RuleDelayed rules where the key corresponds to the form expected from the command, and the value is the expression to run when the input matches form and should take the form:
<|({stringForm_ , desc_String}( cmd_ ))...|>
defaultCommands contains the following commands:
"help" or "h" or "?"print help message
"exit" or "quit" or "q"exit the interface
"eval" or "e"evaluate code in the session
With "POSIX" set to False, short options are not split into single letter shorthands. For example, -abc 10 will be parsed as <|"abc" -> 10|>.
With "POSIX" set to True, short options are split into single letter shorthands. For example, -abc 10 will be parsed as <|"a" -> True, "b" -> True, "c" -> "10"|>.
"ArgumentSpecification" is a List with the following elements:
nboolean flag with long name n.
{n,s}boolean flag long name n and short name s.
{n,s}patoption with long name n and short name s and pattern restriction pat on the argument.
{n,s}patdefoption with long name n and short name s with pattern restriction pat on the argument and default value def.
n and s can be any string.
pat can be any pattern.
def can be any expression.

Examples

Basic Examples (10) 

Parse $CommandLine:

In[1]:=
ResourceFunction["CommandLineTools"]["Parse"]
Out[1]=

By default, the parser has no predefined argument patterns and will accept almost any POSIX form with the exception of single-letter short flags:

In[2]:=
testCommandLine = "command -f -abc 10 --opt=string --list 1,2,3,4";

ResourceFunction["CommandLineTools"]["Parse", "CommandLine" -> testCommandLine]
Out[3]=

Change the session defaults using SetOptions:

In[4]:=
SetOptions[ResourceFunction["CommandLineTools"], "CommandLine" -> testCommandLine];

ResourceFunction["CommandLineTools"]["Parse"]
Out[5]=

Parse for a specific option:

In[6]:=
TableForm @ {
  ResourceFunction["CommandLineTools"]["Parse", "f"], ResourceFunction["CommandLineTools"]["Parse", "opt" | "list"]
  }
Out[6]=

You can enable full POSIX parsing for single-character short options using the "POSIX" option:

In[7]:=
ResourceFunction["CommandLineTools"]["Parse", "POSIX" -> True]
Out[7]=

Define an expected argument pattern and new test command:

In[8]:=
SetOptions[ResourceFunction["CommandLineTools"],
  "CommandLine" -> "command -ab 10 --flag -c abc",
  "POSIX" -> True,
  "ArgumentSpecification" -> {
    "flag",
    {"flag2", "a"},
    {"flag3", "b"} -> _Integer,
    {"flag4", "c"} -> _String -> "default"
    }
  ];

Parse the command line:

In[9]:=
parsed = ResourceFunction["CommandLineTools"]["Parse"]
Out[9]=
In[10]:=
parsed = ResourceFunction["CommandLineTools"]["Parse"];
Dataset[TabularSchema[Tabular @* List @ parsed][
   "RawSchema"]]["ColumnProperties"]
Out[11]=

By default, any unknown arguments will be parsed as strings:

In[12]:=
ResourceFunction["CommandLineTools"]["Parse", "CommandLine" -> "command -ab 10 --flag --other"]
Out[12]=

This behaviour can be changed by disabling the "StrictParse" option:

In[13]:=
ResourceFunction["CommandLineTools"]["Parse",
 "CommandLine" -> "command -ab 10 --flag --other --other2 value",
 "StrictParse" -> True
 ]
Out[13]=

FlagQ (4) 

Use FlagQ to quickly check if an argument is present in the command line:

In[14]:=
ResourceFunction["CommandLineTools"]["FlagQ", "f",
 "CommandLine" -> "command -ab 10 --flag" ]
Out[14]=

Note that this doesn't work with combined, pre-defined shorthand options:

In[15]:=
ResourceFunction["CommandLineTools"]["FlagQ", "a" | "c",
 	"CommandLine" -> "command -ab 10 --flag" ]
Out[15]=

FlagQ is less versatile than Parse but is around 10x faster (with caching on parse):

In[16]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/f945b3a5-0094-4331-9d54-bbd3aee3eb57"]
Out[17]=

FlagQ does not support the combined POSIX shorthand convention:

In[18]:=
ResourceFunction["CommandLineTools"]["FlagQ", "a",
 "CommandLine" -> "command -ab 10 --flag" ]
Out[18]=

Interface (2) 

Interface can be used to create an interactive, blocking dialog with a script with predefined commands:

In[19]:=
ResourceFunction["CommandLineTools"]["Interface", "HelpMessage" -> "Documentation example"]

More custom commands can also be defined using a second argument:

In[20]:=
ResourceFunction["CommandLineTools"]["Interface",
  <|
  "custom" | "c" :> (Print["Running custom command"])
  |>, "HelpMessage" -> "Documentation example"
 ]

Log (3) 

Log is a convenient helper for logging to stdout and to a log file (or any combination of the two). Messages are formatted using ANSI codes which only work within terminal environments:

In[21]:=
ResourceFunction["CommandLineTools"]["Log", "INFO", "Some log message"]
Out[21]=

The message and timestamp is also logged to log file, the location of which can be changed with an option:

In[22]:=
Import["./logs/wls-cli/20250927.log"]
Out[22]=

Create a collection of loggers:

In[23]:=
logInfo = ResourceFunction["CommandLineTools"]["Log", "INFO"];
logError = ResourceFunction["CommandLineTools"]["Log", "ERROR"];

logInfo["Logging something"];
logError["Error"]
Out[24]=

Help (1) 

Help automatically generates a help message based on your options and commands:

In[25]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/9f0742e6-e324-4d57-82d5-08961cc03094"]
In[26]:=
"CommandLineTools documentation example message\\n\\nCommands:\\n\\n\\tc | custom    Print x to the console\\n\\tq | quit      Quit the program\\n\\t? | help      Print help message\\n\\nOptions:\\n\\n\\t--flag      <_?BooleanQ> (default: False)\\n\\t--flag2, -a <_?BooleanQ> (default: False)\\n\\t--flag3, -b <_Integer>\\n\\t--flag4, -c <_String> (default: \"default\")"

Applications (7) 

Define an example script deploying a local WL HTTP server using LocalDeploy:

Export the script:

In[27]:=
Export[
 	"http-example.wls",
 	ToString[InputForm@code] // StringReplace[ Longest["HoldComplete[" ~~ a___ ~~ "]"] :>
    		"#!/bin/wolframscript\n\n" <> a
   	],
 	"Text"
  ]
Out[27]=

Get help on how to run the script:

Run the script:

Evaluate an expression in the session:

Make a request to the server:

In[28]:=
URLExecute["localhost:8888", {"min" -> -20, "max" -> 20}, "SVG"]
Out[28]=

Exit the script using the quit command:

Publisher

Antonis Aristeidou

Requirements

Wolfram Language 12.2 (December 2020) or above

Version History

  • 1.0.0 – 22 October 2025

Related Resources

License Information