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 based on whether a flag matching form is passed 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

ResourceFunction["CommandLineTools"] takes the following options:
"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
"LogStyles"defaultStyleslog type label style rules
"ArgumentSpecification"Noneoption and argument pattern specification
"StrictParse"Falsereturn failure if unknown option is passed
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"|>.
With "POSIX" set to False, short options are not split into single letter shorthands. For example, "-abc 10" will be parsed as <|"abc"10|>.
cmds and the "InterfaceCommands" option expect the form {{pattern,"description"}expr,}.
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
defaultCommands is an Association contain default functions for all the above commands.
The "Interface" blocking loop checks that the variable CommandLineTools`ShouldExit is False to continue blocking, so the "exit" function simply sets this variable to True.
lvl for "Log" can be any string.
"LogStyles" expects the form {"lvl"style,}, where style is typically a color specification.
defaultStyles corresponds to the following rules:
{ "INFO" -> Gray, "WARN" -> Yellow, "SUCC" -> Green, "FAILURE" -> Red, "SUCCESS" -> Green, "FAIL" -> Red, "ERROR" -> Red }
Any "LogType" not matching a known style will be styled Gray.
The "ArgumentSpecification" is a list containing elements of the following forms:
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.

Examples

Basic Examples (4) 

Parse the $CommandLine:

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

Use FlagQ to quickly check if an argument is present in the command line, always returning True or False:

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

Interface creates a blocking interface with predefined commands:

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

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[4]:=
log = ResourceFunction["CommandLineTools"]["Log", "INFO", "Some log message"]
Out[4]=

Scope (12) 

Parse (6) 

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

In[5]:=
ResourceFunction["CommandLineTools"]["Parse",
 	"CommandLine" -> "command -f -abc 10 --opt=string --list 1,2,3,4"
 ]
Out[6]=

To avoid providing options each time CommandLineTools is called, the session defaults can be changed using SetOptions:

In[7]:=
SetOptions[ResourceFunction["CommandLineTools"],
  "CommandLine" -> "command -f -abc 10 --opt=string --list 1,2,3,4"
  ];
ResourceFunction["CommandLineTools"]["Parse"]
Out[8]=

Parse for a specified option:

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

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

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

Define an expected argument pattern and new test command:

In[11]:=
SetOptions[ResourceFunction["CommandLineTools"],
  "CommandLine" -> "command -ab 10 --flag -c abc",
  "POSIX" -> True,
  "ArgumentSpecification" -> {
    "flag",
    {"flag2", "a"},
    {"flag3", "b"} -> _Integer,
    {"flag4", "c"} -> _String -> "default"
    }
  ];
parsed = ResourceFunction["CommandLineTools"]["Parse"];
Dataset[TabularSchema[Tabular @* List @ parsed][
   "RawSchema"]]["ColumnProperties"]
Out[12]=

By default, unknown arguments will be parsed as strings:

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

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

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

FlagQ (2) 

FlagQ parses combined shorthand options if POSIX is set to True:

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

FlagQ is around 10 to 25 times faster than the Parse method:

In[16]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/33c9cbdb-be13-478a-a62a-27bb309ec368"]
Out[13]=

Interface (1) 

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

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

Log (2) 

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[18]:=
log = ResourceFunction["CommandLineTools"]["Log", "INFO", "Some log message"]
Out[18]=

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

In[19]:=
Import[log["Location"], "Text"]
Out[19]=

Create a collection of loggers:

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

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

Help (1) 

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

In[22]:=
(* Evaluate this cell to get the example input *) CloudGet["https://www.wolframcloud.com/obj/1b3fb032-05ce-4802-b378-a14a0adb565a"]
Out[23]=

Applications (7) 

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

Export the script:

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

Get help on how to run the script:

Run the script:

Evaluate an expression in the session:

Make a request to the server:

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

Exit the script using the quit command:

Publisher

Antonis Aristeidou

Requirements

Wolfram Language 13.0 (December 2021) or above

Version History

  • 1.1.0 – 05 December 2025
  • 1.0.0 – 22 October 2025

Related Resources

Author Notes

1.1.0 - Add POSIX support to FlagQ - Wording changes, typos and delimiters - Implement and document LogStyles as an option - More specific option patterns - StrictParse returns failure when no flags found

License Information