1argparse(3) Erlang Module Definition argparse(3)
2
3
4
6 argparse - Command line arguments parser.
7
9 This module implements command line parser. Parser operates with com‐
10 mands and arguments represented as a tree. Commands are branches, and
11 arguments are leaves of the tree. Parser always starts with the root
12 command, named after progname (the name of the program which started
13 Erlang).
14
15 A command specification may contain handler definition for each com‐
16 mand, and a number argument specifications. When parser is successful,
17 argparse calls the matching handler, passing arguments extracted from
18 the command line. Arguments can be positional (occupying specific posi‐
19 tion in the command line), and optional, residing anywhere but prefixed
20 with a specified character.
21
22 argparse automatically generates help and usage messages. It will also
23 issue errors when users give the program invalid arguments.
24
26 argparse is designed to work with escript. The example below is a fully
27 functioning Erlang program accepting two command line arguments and
28 printing their product.
29
30 #!/usr/bin/env escript
31
32 main(Args) ->
33 argparse:run(Args, cli(), #{progname => mul}).
34
35 cli() ->
36 #{
37 arguments => [
38 #{name => left, type => integer},
39 #{name => right, type => integer}
40 ],
41 handler =>
42 fun (#{left := Left, right := Right}) ->
43 io:format("~b~n", [Left * Right])
44 end
45 }.
46
47
48 Running this script with no arguments results in an error, accompanied
49 by the usage information.
50
51 The cli function defines a single command with embedded handler accept‐
52 ing a map. Keys of the map are argument names as defined by the argu‐
53 ment field of the command, left and right in the example. Values are
54 taken from the command line, and converted into integers, as requested
55 by the type specification. Both arguments in the example above are re‐
56 quired (and therefore defined as positional).
57
59 A command may contain nested commands, forming a hierarchy. Arguments
60 defined at the upper level command are automatically added to all
61 nested commands. Nested commands example (assuming progname is nested):
62
63 cli() ->
64 #{
65 %% top level argument applicable to all commands
66 arguments => [#{name => top}],
67 commands => #{
68 "first" => #{
69 %% argument applicable to "first" command and
70 %% all commands nested into "first"
71 arguments => [#{name => mid}],
72 commands => #{
73 "second" => #{
74 %% argument only applicable for "second" command
75 arguments => [#{name => bottom}],
76 handler => fun (A) -> io:format("~p~n", [A]) end
77 }
78 }
79 }
80 }
81 }.
82
83
84 In the example above, a 3-level hierarchy is defined. First is the
85 script itself (nested), accepting the only argument top. Since it has
86 no associated handler, run/3 will not accept user input omitting nested
87 command selection. For this example, user has to supply 5 arguments in
88 the command line, two being command names, and another 3 - required po‐
89 sitional arguments:
90
91 #{top => "one",mid => "two",bottom => "three"}
92
93
94 Commands have preference over positional argument values. In the exam‐
95 ple above, commands and positional arguments are interleaving, and arg‐
96 parse matches command name first.
97
99 argparse supports positional and optional arguments. Optional argu‐
100 ments, or options for short, must be prefixed with a special character
101 (- is the default on all operating systems). Both options and posi‐
102 tional arguments have 1 or more associated values. See argument speci‐
103 fication to find more details about supported combinations.
104
105 In the user input, short options may be concatenated with their values.
106 Long options support values separated by =. Consider this definition:
107
108 cli() ->
109 #{
110 arguments => [
111 #{name => long, long => "-long"},
112 #{name => short, short => $s}
113 ],
114 handler => fun (Args) -> io:format("~p~n", [Args]) end
115 }.
116
117
118 Running ./args --long=VALUE prints #{long => "VALUE"}, running ./args
119 -sVALUE prints #{short => "VALUE"}
120
121 argparse supports boolean flags concatenation: it is possible to
122 shorten -r -f -v to -rfv.
123
124 Shortened option names are not supported: it is not possible to use
125 --my-argum instead of --my-argument-name even when such option can be
126 unambiguously found.
127
129 arg_type() =
130 boolean | float |
131 {float, Choice :: [float()]} |
132 {float, [{min, float()} | {max, float()}]} |
133 integer |
134 {integer, Choices :: [integer()]} |
135 {integer, [{min, integer()} | {max, integer()}]} |
136 string |
137 {string, Choices :: [string()]} |
138 {string, Re :: string()} |
139 {string, Re :: string(), ReOptions :: [term()]} |
140 binary |
141 {binary, Choices :: [binary()]} |
142 {binary, Re :: binary()} |
143 {binary, Re :: binary(), ReOptions :: [term()]} |
144 atom |
145 {atom, Choices :: [atom()]} |
146 {atom, unsafe} |
147 {custom, fun((string()) -> term())}
148
149 Defines type conversion applied to the string retrieved from the
150 user input. If the conversion is successful, resulting value is
151 validated using optional Choices, or minimums and maximums (for
152 integer and floating point values only). Strings and binary val‐
153 ues may be validated using regular expressions. It's possible to
154 define custom type conversion function, accepting a string and
155 returning Erlang term. If this function raises error with badarg
156 reason, argument is treated as invalid.
157
158 argument_help() =
159 {unicode:chardata(),
160 [unicode:chardata() | type | default] |
161 fun(() -> unicode:chardata())}
162
163 User-defined help template to print in the command usage. First
164 element of a tuple must be a string. It is printed as a part of
165 the usage header. Second element of the tuple can be either a
166 string printed as-is, a list containing strings, type and de‐
167 fault atoms, or a user-defined function that must return a
168 string.
169
170 argument_name() = atom() | string() | binary()
171
172 Argument name is used to populate argument map.
173
174 argument() =
175 #{name := argument_name(),
176 short => char(),
177 long => string(),
178 required => boolean(),
179 default => term(),
180 type => arg_type(),
181 action =>
182 store |
183 {store, term()} |
184 append |
185 {append, term()} |
186 count | extend,
187 nargs =>
188 integer() >= 1 |
189 maybe |
190 {maybe, term()} |
191 list | nonempty_list | all,
192 help => hidden | unicode:chardata() | argument_help()}
193
194 Argument specification. Defines a single named argument that is
195 returned in the argument map. The only required field is name,
196 all other fields have defaults.
197
198 If either of the short or long fields is specified, the argument
199 is treated as optional. Optional arguments do not have specific
200 order and may appear anywhere in the command line. Positional
201 arguments are ordered the same way as they appear in the argu‐
202 ments list of the command specification.
203
204 By default, all positional arguments must be present in the com‐
205 mand line. The parser will return an error otherwise. Options,
206 however, may be omitted, in which case resulting argument map
207 will either contain the default value, or not have the key at
208 all.
209
210 name:
211 Sets the argument name in the parsed argument map. If help
212 is not defined, name is also used to generate the default
213 usage message.
214
215 short:
216 Defines a short (single character) form of an optional argu‐
217 ment.
218
219 %% Define a command accepting argument named myarg, with short form $a:
220 1> Cmd = #{arguments => [#{name => myarg, short => $a}]}.
221 %% Parse command line "-a str":
222 2> {ok, ArgMap, _, _} = argparse:parse(["-a", "str"], Cmd), ArgMap.
223
224 #{myarg => "str"}
225
226 %% Option value can be concatenated with the switch: "-astr"
227 3> {ok, ArgMap, _, _} = argparse:parse(["-astr"], Cmd), ArgMap.
228
229 #{myarg => "str"}
230
231
232 By default all options expect a single value following the
233 option switch. The only exception is an option of a boolean
234 type.
235
236 long:
237 Defines a long form of an optional argument.
238
239 1> Cmd = #{arguments => [#{name => myarg, long => "name"}]}.
240 %% Parse command line "-name Erlang":
241 2> {ok, ArgMap, _, _} = argparse:parse(["-name", "Erlang"], Cmd), ArgMap.
242
243 #{myarg => "Erlang"}
244 %% Or use "=" to separate the switch and the value:
245 3> {ok, ArgMap, _, _} = argparse:parse(["-name=Erlang"], Cmd), ArgMap.
246
247 #{myarg => "Erlang"}
248
249
250 If neither short not long is defined, the argument is
251 treated as positional.
252
253 required:
254 Forces the parser to expect the argument to be present in
255 the command line. By default, all positional argument are
256 required, and all options are not.
257
258 default:
259 Specifies the default value to put in the parsed argument
260 map if the value is not supplied in the command line.
261
262 1> argparse:parse([], #{arguments => [#{name => myarg, short => $m}]}).
263
264 {ok,#{}, ...
265 2> argparse:parse([], #{arguments => [#{name => myarg, short => $m, default => "def"}]}).
266
267 {ok,#{myarg => "def"}, ...
268
269
270 type:
271 Defines type conversion and validation routine. The default
272 is string, assuming no conversion.
273
274 nargs:
275 Defines the number of following arguments to consume from
276 the command line. By default, the parser consumes the next
277 argument and converts it into an Erlang term according to
278 the specified type.
279
280 pos_integer():
281 Consume exactly this number of positional arguments, fail
282 if there is not enough. Value in the argument map contains
283 a list of exactly this length. Example, defining a posi‐
284 tional argument expecting 3 integer values:
285
286 1> Cmd = #{arguments => [#{name => ints, type => integer, nargs => 3}]},
287 argparse:parse(["1", "2", "3"], Cmd).
288
289 {ok, #{ints => [1, 2, 3]}, ...
290
291
292 Another example defining an option accepted as -env and
293 expecting two string arguments:
294
295 1> Cmd = #{arguments => [#{name => env, long => "env", nargs => 2}]},
296 argparse:parse(["-env", "key", "value"], Cmd).
297
298 {ok, #{env => ["key", "value"]}, ...
299
300
301 list:
302 Consume all following arguments until hitting the next op‐
303 tion (starting with an option prefix). May result in an
304 empty list added to the arguments map.
305
306 1> Cmd = #{arguments => [
307 #{name => nodes, long => "nodes", nargs => list},
308 #{name => verbose, short => $v, type => boolean}
309 ]},
310 argparse:parse(["-nodes", "one", "two", "-v"], Cmd).
311
312 {ok, #{nodes => ["one", "two"], verbose => true}, ...
313
314
315 nonempty_list:
316 Same as list, but expects at least one argument. Returns
317 an error if the following command line argument is an op‐
318 tion switch (starting with the prefix).
319
320 'maybe':
321 Consumes the next argument from the command line, if it
322 does not start with an option prefix. Otherwise, adds a
323 default value to the arguments map.
324
325 1> Cmd = #{arguments => [
326 #{name => level, short => $l, nargs => 'maybe', default => "error"},
327 #{name => verbose, short => $v, type => boolean}
328 ]},
329 argparse:parse(["-l", "info", "-v"], Cmd).
330
331 {ok,#{level => "info",verbose => true}, ...
332
333 %% When "info" is omitted, argument maps receives the default "error"
334 2> argparse:parse(["-l", "-v"], Cmd).
335
336 {ok,#{level => "error",verbose => true}, ...
337
338
339 {'maybe', term()}:
340 Consumes the next argument from the command line, if it
341 does not start with an option prefix. Otherwise, adds a
342 specified Erlang term to the arguments map.
343
344 all:
345 Fold all remaining command line arguments into a list, ig‐
346 noring any option prefixes or switches. Useful for proxy‐
347 ing arguments into another command line utility.
348
349 1> Cmd = #{arguments => [
350 #{name => verbose, short => $v, type => boolean},
351 #{name => raw, long => "-", nargs => all}
352 ]},
353 argparse:parse(["-v", "--", "-kernel", "arg", "opt"], Cmd).
354
355 {ok,#{raw => ["-kernel","arg","opt"],verbose => true}, ...
356
357
358 action:
359 Defines an action to take when the argument is found in the
360 command line. The default action is store.
361
362 store:
363 Store the value in the arguments map. Overwrites the value
364 previously written.
365
366 1> Cmd = #{arguments => [#{name => str, short => $s}]},
367 argparse:parse(["-s", "one", "-s", "two"], Cmd).
368
369 {ok, #{str => "two"}, ...
370
371
372 {store, term()}:
373 Stores the specified term instead of reading the value
374 from the command line.
375
376 1> Cmd = #{arguments => [#{name => str, short => $s, action => {store, "two"}}]},
377 argparse:parse(["-s"], Cmd).
378
379 {ok, #{str => "two"}, ...
380
381
382 append:
383 Appends the repeating occurrences of the argument instead
384 of overwriting.
385
386 1> Cmd = #{arguments => [#{name => node, short => $n, action => append}]},
387 argparse:parse(["-n", "one", "-n", "two", "-n", "three"], Cmd).
388
389 {ok, #{node => ["one", "two", "three"]}, ...
390
391 %% Always produces a list - even if there is one occurrence
392 2> argparse:parse(["-n", "one"], Cmd).
393
394 {ok, #{node => ["one"]}, ...
395
396
397 {append, term()}:
398 Same as append, but instead of consuming the argument from
399 the command line, appends a provided term().
400
401 count:
402 Puts a counter as a value in the arguments map. Useful for
403 implementing verbosity option:
404
405 1> Cmd = #{arguments => [#{name => verbose, short => $v, action => count}]},
406 argparse:parse(["-v"], Cmd).
407
408 {ok, #{verbose => 1}, ...
409
410 2> argparse:parse(["-vvvv"], Cmd).
411
412 {ok, #{verbose => 4}, ...
413
414
415 extend:
416 Works as append, but flattens the resulting list. Valid
417 only for nargs set to list, nonempty_list, all or pos_in‐
418 teger().
419
420 1> Cmd = #{arguments => [#{name => duet, short => $d, nargs => 2, action => extend}]},
421 argparse:parse(["-d", "a", "b", "-d", "c", "d"], Cmd).
422
423 {ok, #{duet => ["a", "b", "c", "d"]}, ...
424
425 %% 'append' would result in {ok, #{duet => [["a", "b"],["c", "d"]]},
426
427
428 help:
429 Specifies help/usage text for the argument. argparse pro‐
430 vides automatic generation based on the argument name, type
431 and default value, but for better usability it is recom‐
432 mended to have a proper description. Setting this field to
433 hidden suppresses usage output for this argument.
434
435 arg_map() = #{argument_name() => term()}
436
437 Arguments map is the map of argument names to the values ex‐
438 tracted from the command line. It is passed to the matching com‐
439 mand handler. If an argument is omitted, but has the default
440 value is specified, it is added to the map. When no default
441 value specified, and argument is not present in the command
442 line, corresponding key is not present in the resulting map.
443
444 handler() =
445 optional |
446 fun((arg_map()) -> term()) |
447 {module(), Fn :: atom()} |
448 {fun(() -> term()), term()} |
449 {module(), atom(), term()}
450
451 Command handler specification. Called by run/3 upon successful
452 parser return.
453
454 fun((arg_map()) -> term()):
455 Function accepting argument map. See the basic example in
456 the Quick Start section.
457
458 {Module :: module(), Function :: atom()}:
459 Function named Function, exported from Module, accepting ar‐
460 gument map.
461
462 {fun(() -> term()), Default :: term()}:
463 Function accepting as many arguments as there are in the ar‐
464 guments list for this command. Arguments missing from the
465 parsed map are replaced with the Default. Convenient way to
466 expose existing functions.
467
468 1> Cmd = #{arguments => [
469 #{name => x, type => float},
470 #{name => y, type => float, short => $p}],
471 handler => {fun math:pow/2, 1}},
472 argparse:run(["2", "-p", "3"], Cmd, #{}).
473
474 8.0
475
476 %% default term 1 is passed to math:pow/2
477 2> argparse:run(["2"], Cmd, #{}).
478
479 2.0
480
481
482 {Module :: module(), Function :: atom(), Default :: term()}:
483 Function named Function, exported from Module, accepting as
484 many arguments as defined for this command. Arguments miss‐
485 ing from the parsed map are replaced with the Default. Ef‐
486 fectively, just a different syntax to the same functionality
487 as demonstrated in the code above.
488
489 command_help() =
490 [unicode:chardata() | usage | commands | arguments | options]
491
492 User-defined help template. Use this option to mix custom and
493 predefined usage text. Help template may contain unicode
494 strings, and following atoms:
495
496 usage:
497 Formatted command line usage text, e.g. rm [-rf] <direc‐
498 tory>.
499
500 commands:
501 Expanded list of sub-commands.
502
503 arguments:
504 Detailed description of positional arguments.
505
506 options:
507 Detailed description of optional arguments.
508
509 command() =
510 #{commands => #{string() => command()},
511 arguments => [argument()],
512 help => hidden | unicode:chardata() | command_help(),
513 handler => handler()}
514
515 Command specification. May contain nested commands, forming a
516 hierarchy.
517
518 commands:
519 Maps of nested commands. Keys must be strings, matching com‐
520 mand line input. Basic utilities do not need to specify any
521 nested commands.
522
523 arguments:
524 List of arguments accepted by this command, and all nested
525 commands in the hierarchy.
526
527 help:
528 Specifies help/usage text for this command. Pass hidden to
529 remove this command from the usage output.
530
531 handler:
532 Specifies a callback function to call by run/3 when the
533 parser is successful.
534
535 cmd_path() = [string()]
536
537 Path to the nested command. First element is always the prog‐
538 name, subsequent elements are nested command names.
539
540 parser_error() =
541 {Path :: cmd_path(),
542 Expected :: argument() | undefined,
543 Actual :: string() | undefined,
544 Details :: unicode:chardata()}
545
546 Returned from parse/2,3 when the user input cannot be parsed ac‐
547 cording to the command specification.
548
549 First element is the path to the command that was considered
550 when the parser detected an error. Second element, Expected, is
551 the argument specification that caused an error. It could be un‐
552 defined, meaning that Actual argument had no corresponding spec‐
553 ification in the arguments list for the current command.
554
555 When Actual is set to undefined, it means that a required argu‐
556 ment is missing from the command line. If both Expected and Ac‐
557 tual have values, it means validation error.
558
559 Use format_error/1 to generate a human-readable error descrip‐
560 tion, unless there is a need to provide localised error mes‐
561 sages.
562
563 parser_options() =
564 #{prefixes => [char()],
565 default => term(),
566 progname => string() | atom(),
567 command => cmd_path(),
568 columns => integer() >= 1}
569
570 Options changing parser behaviour.
571
572 prefixes:
573 Changes the option prefix (the default is -).
574
575 default:
576 Specifies the default value for all optional arguments. When
577 this field is set, resulting argument map will contain all
578 argument names. Useful for easy pattern matching on the ar‐
579 gument map in the handler function.
580
581 progname:
582 Specifies the program (root command) name. Returned as the
583 first element of the command path, and printed in help/usage
584 text. It is recommended to have this value set, otherwise
585 the default one is determined with init:get_argument(prog‐
586 name) and is often set to erl instead of the actual script
587 name.
588
589 command:
590 Specifies the path to the nested command for help/2. Useful
591 to limit output for complex utilities with multiple com‐
592 mands, and used by the default error handling logic.
593
594 columns:
595 Specifies the help/usage text width (characters) for help/2.
596 Default value is 80.
597
598 parse_result() =
599 {ok, arg_map(), Path :: cmd_path(), command()} |
600 {error, parser_error()}
601
602 Returned from parse/2,3. Contains arguments extracted from the
603 command line, path to the nested command (if any), and a (poten‐
604 tially nested) command specification that was considered when
605 the parser finished successfully. It is expected that the com‐
606 mand contains a handler definition, that will be called passing
607 the argument map.
608
610 format_error(Reason :: parser_error()) -> unicode:chardata()
611
612 Generates human-readable text for parser error. Does not include
613 help/usage information, and does not provide localisation.
614
615 help(Command :: command()) -> string()
616
617 help(Command :: command(), Options :: parser_options()) ->
618 unicode:chardata()
619
620 Generates help/usage information text for the command supplied,
621 or any nested command when command option is specified. Does not
622 provide localisaton. Expects progname to be set, otherwise de‐
623 faults to return value of init:get_argument(progname).
624
625 parse(Args :: [string()], Command :: command()) -> parse_result()
626
627 parse(Args :: [string()],
628 Command :: command(),
629 Options :: parser_options()) ->
630 parse_result()
631
632 Parses command line arguments according to the command specifi‐
633 cation. Raises an exception if the command specification is not
634 valid. Use erl_error:format_exception/3,4 to see a friendlier
635 message. Invalid command line input does not raise an exception,
636 but makes parse/2,3 to return a tuple {error, parser_error()}.
637
638 This function does not call command handler.
639
640 run(Args :: [string()],
641 Command :: command(),
642 Options :: parser_options()) ->
643 term()
644
645 Parses command line arguments and calls the matching command
646 handler. Prints human-readable error, help/usage information for
647 the discovered command, and halts the emulator with code 1 if
648 there is any error in the command specification or user-provided
649 command line input.
650
651 Warning:
652 This function is designed to work as an entry point to a stand‐
653 alone escript. Therefore, it halts the emulator for any error
654 detected. Do not use this function through remote procedure
655 call, or it may result in an unexpected shutdown of a remote
656 node.
657
658
659
660
661Maxim Fedorov stdlib 5.1.1 argparse(3)