The most simple code may be the following (extracted from the documentation):
var verbose: boolean; threads: integer; ... with Executable.Command do begin ExeDescription := 'An executable to test mORMot Execute.Command'; verbose := Option(['v', 'verbose'], 'generate verbose output'); Get(['t', 'threads'], threads, '#number of threads to run', 5); ConsoleWrite(FullDescription); end;
This code will fill verbose
and threads
local variables from the command line (with some optional default value), and output on Linux:
An executable to test mORMot Execute.Command Usage: mormot2tests [options] [params] Options: -v, --verbose generate verbose output Params: -t, --threads <number> (default 5) number of threads to run
So, not only you can parse the command line and retrieve values, but you can also add some description text, and let generate an accurate help message when needed.
You can note that the #
character is used to mark the keyword to be used as value name for a given parameter, to make the text more meaningful.
For instance, '#number of threads to run'
will generate a nice -t, --threads <number>
text for the parameter description.
For a most typical use case, you may look at our TFB Benchmarking Sample source code:
// parse command line parameters with Executable.Command do begin ExeDescription := 'TFB Server using mORMot 2'; if Option(['p', 'pin'], 'pin each server to a CPU') then pinServers2Cores := true; if Option('nopin', 'disable the CPU pinning') then pinServers2Cores := false; // no option would keep the default boolean Get(['s', 'servers'], servers, '#count of servers (listener sockets)', servers); Get(['t', 'threads'], threads, 'per-server thread pool #size', threads); if Option(['?', 'help'], 'display this message') then begin ConsoleWrite(FullDescription); exit; end; if ConsoleWriteUnknown then exit; end;
This would generate such a description:
d:\dev\lib2\ex\techempower-bench\exe>raw /? TFB Server using mORMot 2 Usage: raw [options] [params] Options: /p, /pin pin each server to a CPU /nopin disable the CPU pinning /?, /help display this message Params: /s, /servers <count> (default 1) count of servers (listener sockets) /t, /threads <size> (default 8) per-server thread pool size
It will accept commands like this on Windows:
raw /p /t=10 raw /t 10 /s 2 /pin raw /servers=2 /threads=8 /nopin raw /servers 2 /threads 8 /nopin
And, on Linux/POSIX, you could write as usual:
./raw -p -t=10 ./raw -t 10 -s 2 --pin ./raw --servers=2 --threads=8 --nopin ./raw --servers 2 --threads 8 --nopin
Note that both -t 10
and -t=10
syntax are accepted.
As you may have guessed it, ConsoleWriteUnknown
is able to notify the user that a wrong switch has been used - and display the help message.
This function is available in the base mormot.core.os.pas unit of the framework.
And feedback is welcome in our forum, as usual!
We hope you find it useful!