On this page
std.getopt
Processing of command line options.
The getopt module implements a getopt function, which adheres to the POSIX syntax for command line options. GNU extensions are supported in the form of long options introduced by a double dash ("--"). Support for bundling of command line options, as was the case with the more traditional single-letter approach, is provided but not enabled by default.
- License:
- Boost License 1.0.
- Authors:
- Andrei Alexandrescu
- Credits
- 
    This module and its documentation are inspired by Perl's Getopt::Long module. The syntax of D's getoptis simpler than its Perl counterpart becausegetoptinfers the expected parameter types from the static types of the passed-in pointers.
- Source
- std/getopt.d
- class GetOptException: object.Exception;
- 
    Thrown on one of the following conditions: - An unrecognized command-line argument is passed, and std.getopt.config.passThroughwas not present.
- A command-line option was not found, and std.getopt.config.requiredwas present.
 
- An unrecognized command-line argument is passed, and 
- GetoptResult getopt(T...)(ref string[] args, T opts);
- 
    Parse and remove command line options from a string array. - Synopsis
 
 Theimport std.getopt; string data = "file.dat"; int length = 24; bool verbose; enum Color { no, yes }; Color color; void main(string[] args) { auto helpInformation = getopt( args, "length", &length, // numeric "file", &data, // string "verbose", &verbose, // flag "color", "Information about this color", &color); // enum ... if (helpInformation.helpWanted) { defaultGetoptPrinter("Some information about the program.", helpInformation.options); } }getoptfunction takes a reference to the command line (as received bymain) as its first argument, and an unbounded number of pairs of strings and pointers. Each string is an option meant to "fill" the value referenced by the pointer to its right (the "bound" pointer). The option string in the call togetoptshould not start with a dash. In all cases, the command-line options that were parsed and used bygetoptare removed fromargs. Whatever in the arguments did not look like an option is left inargsfor further processing by the program. Values that were unaffected by the options are not touched, so a common idiom is to initialize options to their defaults and then invokegetopt. If a command-line argument is recognized as an option with a parameter and the parameter cannot be parsed properly (e.g., a number is expected but not present), aConvExceptionexception is thrown. Ifstd.getopt.config.passThroughwas not passed togetoptand an unrecognized command-line argument is found, aGetOptExceptionis thrown. Depending on the type of the pointer being bound,getoptrecognizes the following kinds of options:- Boolean options. A lone argument sets the option to true. Additionally true or false can be set within the option separated with an "=" sign:
 To setbool verbose = false, debugging = true; getopt(args, "verbose", &verbose, "debug", &debugging);verbosetotrue, invoke the program with either--verboseor--verbose=true. To setdebuggingtofalse, invoke the program with--debugging=false.
- Numeric options. If an option is bound to a numeric type, a number is expected as the next option, or right within the option separated with an "=" sign: 
 To setuint timeout; getopt(args, "timeout", &timeout);timeoutto5, invoke the program with either--timeout=5or--timeout 5.
- Incremental options. If an option name has a "+" suffix and is bound to a numeric type, then the option's value tracks the number of times the option occurred on the command line: 
 Invoking the program with "--paranoid --paranoid --paranoid" will setuint paranoid; getopt(args, "paranoid+", ¶noid);paranoidto 3. Note that an incremental option never expects a parameter, e.g., in the command line "--paranoid 42 --paranoid", the "42" does not setparanoidto 42; instead,paranoidis set to 2 and "42" is not considered as part of the normal program arguments.
- Enum options. If an option is bound to an enum, an enum symbol as a string is expected as the next option, or right within the option separated with an "=" sign: 
 To setenum Color { no, yes }; Color color; // default initialized to Color.no getopt(args, "color", &color);colortoColor.yes, invoke the program with either--color=yesor--color yes.
- String options. If an option is bound to a string, a string is expected as the next option, or right within the option separated with an "=" sign: 
 Invoking the program with "--output=myfile.txt" or "--output myfile.txt" will setstring outputFile; getopt(args, "output", &outputFile);outputFileto "myfile.txt". If you want to pass a string containing spaces, you need to use the quoting that is appropriate to your shell, e.g. --output='my file.txt'.
- Array options. If an option is bound to an array, a new element is appended to the array each time the option occurs: 
 Invoking the program with "--output=myfile.txt --output=yourfile.txt" or "--output myfile.txt --output yourfile.txt" will setstring[] outputFiles; getopt(args, "output", &outputFiles);outputFilesto[ "myfile.txt", "yourfile.txt" ]. Alternatively you can setarraySepto allow multiple elements in one parameter.
 With the above code you can invoke the program with "--output=myfile.txt,yourfile.txt", or "--output myfile.txt,yourfile.txt".string[] outputFiles; arraySep = ","; // defaults to "", meaning one element per parameter getopt(args, "output", &outputFiles);
- Hash options. If an option is bound to an associative array, a string of the form "name=value" is expected as the next option, or right within the option separated with an "=" sign: 
 Invoking the program with e.g. "--tune=alpha=0.5 --tune beta=0.6" will setdouble[string] tuningParms; getopt(args, "tune", &tuningParms);tuningParmsto [ "alpha" : 0.5, "beta" : 0.6 ]. Alternatively you can setarraySepas the element separator:
 With the above code you can invoke the program with "--tune=alpha=0.5,beta=0.6", or "--tune alpha=0.5,beta=0.6". In general, the keys and values can be of any parsable types.double[string] tuningParms; arraySep = ","; // defaults to "", meaning one element per parameter getopt(args, "tune", &tuningParms);
- Callback options. An option can be bound to a function or delegate with the signature void function(),void function(string option),void function(string option, string value), or their delegate equivalents.- If the callback doesn't take any arguments, the callback is invoked whenever the option is seen.
- If the callback takes one string argument, the option string (without the leading dash(es)) is passed to the callback. After that, the option string is considered handled and removed from the options array. void main(string[] args) { uint verbosityLevel = 1; void myHandler(string option) { if (option == "quiet") { verbosityLevel = 0; } else { assert(option == "verbose"); verbosityLevel = 2; } } getopt(args, "verbose", &myHandler, "quiet", &myHandler); }
- If the callback takes two string arguments, the option string is handled as an option with one argument, and parsed accordingly. The option and its value are passed to the callback. After that, whatever was passed to the callback is considered handled and removed from the list. int main(string[] args) { uint verbosityLevel = 1; bool handlerFailed = false; void myHandler(string option, string value) { switch (value) { case "quiet": verbosityLevel = 0; break; case "verbose": verbosityLevel = 2; break; case "shouting": verbosityLevel = verbosityLevel.max; break; default : stderr.writeln("Unknown verbosity level ", value); handlerFailed = true; break; } } getopt(args, "verbosity", &myHandler); return handlerFailed ? 1 : 0; }
 
 - Options with multiple names
- Sometimes option synonyms are desirable, e.g. "--verbose", "--loquacious", and "--garrulous" should have the same effect. Such alternate option names can be included in the option specification, using "|" as a separator:
 bool verbose; getopt(args, "verbose|loquacious|garrulous", &verbose);- Case
- 
      By default options are case-insensitive. You can change that behavior by passing getoptthecaseSensitivedirective like this:
 
 In the example above, "--foo" and "--bar" are recognized, but "--Foo", "--Bar", "--FOo", "--bAr", etc. are rejected. The directive is active until the end ofbool foo, bar; getopt(args, std.getopt.config.caseSensitive, "foo", &foo, "bar", &bar);getopt, or until the converse directivecaseInsensitiveis encountered:
 The option "--Foo" is rejected due tobool foo, bar; getopt(args, std.getopt.config.caseSensitive, "foo", &foo, std.getopt.config.caseInsensitive, "bar", &bar);std.getopt.config.caseSensitive, but not "--Bar", "--bAr" etc. because the directivestd.getopt.config.caseInsensitiveturned sensitivity off before option "bar" was parsed.- Short versus long options
- 
      Traditionally, programs accepted single-letter options preceded by only one dash (e.g. -t).getoptaccepts such parameters seamlessly. When used with a double-dash (e.g.--t), a single-letter option behaves the same as a multi-letter option. When used with a single dash, a single-letter option is accepted.
 timeoutto5, use either of the following:--timeout=5,--timeout 5,--t=5,--t 5,-t5, or-t 5. Forms such as-timeout=5will be not accepted. For more details about short options, refer also to the next section.- Bundling
- 
      Single-letter options can be bundled together, i.e. "-abc" is the same as "-a -b -c". By default, this option is turned off. You can turn it on with thestd.getopt.config.bundlingdirective:
 
 In case you want to only enable bundling for some of the parameters, bundling can be turned off withbool foo, bar; getopt(args, std.getopt.config.bundling, "foo|f", &foo, "bar|b", &bar);std.getopt.config.noBundling.- Required
- An option can be marked as required. If that option is not present in the arguments an exception will be thrown.
 
 Only the option directly followingbool foo, bar; getopt(args, std.getopt.config.required, "foo|f", &foo, "bar|b", &bar);std.getopt.config.requiredis required.- Passing unrecognized options through
- 
      If an application needs to do its own processing of whichever arguments getoptdid not understand, it can pass thestd.getopt.config.passThroughdirective togetopt:
 
 An unrecognized option such as "--baz" will be found untouched inbool foo, bar; getopt(args, std.getopt.config.passThrough, "foo", &foo, "bar", &bar);argsaftergetoptreturns.- Help Information Generation
- 
      If an option string is followed by another string, this string serves as a description for this option. The getoptfunction returns a struct of typeGetoptResult. This return value contains information about all passed options as well abool GetoptResult.helpWantedflag indicating whether information about these options was requested. Thegetoptfunction always adds an option for--help|-hto set the flag if the option is seen on the command line.
 - Options Terminator
- 
      A lone double-dash terminates getoptgathering. It is used to separate program options from other parameters (e.g., options to be passed to another program). Invoking the example above with"--foo -- --bar"parses foo but leaves "--bar" inargs. The double-dash itself is removed from the argument array unless thestd.getopt.config.keepEndOfOptionsdirective is given.
 - Examples:
- 
      auto args = ["prog", "--foo", "-b"]; bool foo; bool bar; auto rslt = getopt(args, "foo|f", "Some information about foo.", &foo, "bar|b", "Some help message about bar.", &bar); if (rslt.helpWanted) { defaultGetoptPrinter("Some information about the program.", rslt.options); }
 
- enum config: int;
- 
    Configuration options for getopt.You can pass them to getoptin any position, except in between an option string and its bound pointer.- caseSensitive
- 
      Turn case sensitivity on 
- caseInsensitive
- 
      Turn case sensitivity off (default) 
- bundling
- 
      Turn bundling on 
- noBundling
- 
      Turn bundling off (default) 
- passThrough
- 
      Pass unrecognized arguments through 
- noPassThrough
- 
      Signal unrecognized arguments as errors (default) 
- stopOnFirstNonOption
- 
      Stop at first argument that does not look like an option 
- keepEndOfOptions
- 
      Do not erase the endOfOptions separator from args 
- required
- 
      Make the next option a required option 
 
- struct GetoptResult;
- 
    The result of the getoptfunction.helpWantedis set if the option--helpor-hwas passed to the option parser.- bool helpWanted;
- 
      Flag indicating if help was requested 
- Option[] options;
- 
      All possible options 
 
- struct Option;
- 
    Information about an option. - string optShort;
- 
      The short symbol for this option 
- string optLong;
- 
      The long symbol for this option 
- string help;
- 
      The description of this option 
- bool required;
- 
      If a option is required, not passing it will result in an error 
 
- dchar optionChar;
- 
    The option character (default '-'). Defaults to '-' but it can be assigned to prior to calling getopt.
- string endOfOptions;
- 
    The string that conventionally marks the end of all options (default '--'). Defaults to "--" but can be assigned to prior to calling getopt. Assigning an empty string toendOfOptionseffectively disables it.
- dchar assignChar;
- 
    The assignment character used in options with parameters (default '='). Defaults to '=' but can be assigned to prior to calling getopt.
- string arraySep;
- 
    When set to "", parameters to array and associative array receivers are treated as an individual argument. That is, only one argument is appended or inserted per appearance of the option switch. If arraySepis set to something else, then each parameter is first split by the separator, and the individual pieces are treated as arguments to the same option.Defaults to "" but can be assigned to prior to calling getopt.
- void defaultGetoptPrinter(string text, Option[] opt);
- 
    This function prints the passed Options and text in an aligned manner onstdout.The passed text will be printed first, followed by a newline, then the short and long version of every option will be printed. The short and long version will be aligned to the longest option of every Optionpassed. If the option is required, then "Required:" will be printed after the long version of theOption. If a help message is present it will be printed next. The format is illustrated by this code:foreach (it; opt) { writefln("%*s %*s%s%s", lengthOfLongestShortOption, it.optShort, lengthOfLongestLongOption, it.optLong, it.required ? " Required: " : " ", it.help); }- Parameters:
- 
      string textThe text to printed at the beginning of the help output. Option[] optThe Optionextracted from thegetoptparameter.
 
- void defaultGetoptFormatter(Output)(Output output, string text, Option[] opt, string style = "%*s %*s%*s%s\x0a");
- 
    This function writes the passed text and Optioninto an output range in the manner described in the documentation of functiondefaultGetoptPrinter, unless the style option is used.- Parameters:
- 
      Output outputThe output range used to write the help information. string textThe text to print at the beginning of the help output. Option[] optThe Optionextracted from thegetoptparameter.string styleThe manner in which to display the output of each Option.
 
© 1999–2021 The D Language Foundation
Licensed under the Boost License 1.0.
 https://dlang.org/phobos/std_getopt.html