Update documentation [ci skip]

This commit is contained in:
Peter Melnichenko
2018-04-12 14:02:37 +03:00
parent 9019b4fe3a
commit 99cdddbc9d
10 changed files with 417 additions and 144 deletions

View File

@@ -3,12 +3,14 @@ Adding and configuring arguments
Positional arguments can be added using ``:argument(name, description, default, convert, args)`` method. It returns an Argument instance, which can be configured in the same way as Parsers. The ``name`` property is required. Positional arguments can be added using ``:argument(name, description, default, convert, args)`` method. It returns an Argument instance, which can be configured in the same way as Parsers. The ``name`` property is required.
This and the following examples show contents of the result table returned by `parser:parse()` when the script is executed with given command-line arguments.
.. code-block:: lua .. code-block:: lua
:linenos: :linenos:
parser:argument "input" parser:argument "input"
:: .. code-block:: none
$ lua script.lua foo $ lua script.lua foo
@@ -46,7 +48,7 @@ If more than one argument can be consumed, a table is used to store the data.
parser:argument("optional", "An optional argument.") parser:argument("optional", "An optional argument.")
:args "?" :args "?"
:: .. code-block:: none
$ lua script.lua foo bar $ lua script.lua foo bar
@@ -56,7 +58,7 @@ If more than one argument can be consumed, a table is used to store the data.
pair = {"foo", "bar"} pair = {"foo", "bar"}
} }
:: .. code-block:: none
$ lua script.lua foo bar baz $ lua script.lua foo bar baz

View File

@@ -14,7 +14,7 @@ argparse can perform automatic validation and conversion on arguments. If ``conv
parser:option "-t --times" parser:option "-t --times"
:convert(tonumber) :convert(tonumber)
:: .. code-block:: none
$ lua script.lua foo.txt -t5 $ lua script.lua foo.txt -t5
@@ -25,30 +25,52 @@ argparse can perform automatic validation and conversion on arguments. If ``conv
times = 5 times = 5
} }
:: .. code-block:: none
$ lua script.lua nonexistent.txt $ lua script.lua nonexistent.txt
:: .. code-block:: none
Usage: script.lua [-t <times>] [-h] <input> Usage: script.lua [-t <times>] [-h] <input>
Error: nonexistent.txt: No such file or directory Error: nonexistent.txt: No such file or directory
:: .. code-block:: none
$ lua script.lua foo.txt --times=many $ lua script.lua foo.txt --times=many
:: .. code-block:: none
Usage: script.lua [-t <times>] [-h] <input> Usage: script.lua [-t <times>] [-h] <input>
Error: malformed argument 'many' Error: malformed argument 'many'
If ``convert`` property of an element is an array of functions, they will be used as converters for corresponding arguments
in case the element accepts multiple arguments.
.. code-block:: lua
:linenos:
parser:option "--line-style"
:args(2)
:convert {string.lower, tonumber}
.. code-block:: none
$ lua script.lua --line-style DASHED 1.5
.. code-block:: lua
{
line_style = {"dashed", 1.5}
}
Table converters Table converters
^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
If convert property of an element is a table, arguments passed to it will be used as keys. If a key is missing, an error is raised. If convert property of an element is a table and doesn't have functions in array part,
arguments passed to it will be used as keys. If a key is missing, an error is raised.
.. code-block:: lua .. code-block:: lua
:linenos: :linenos:
@@ -59,7 +81,7 @@ If convert property of an element is a table, arguments passed to it will be use
bar = "Something bar-related" bar = "Something bar-related"
} }
:: .. code-block:: none
$ lua script.lua bar $ lua script.lua bar
@@ -69,11 +91,11 @@ If convert property of an element is a table, arguments passed to it will be use
choice = "Something bar-related" choice = "Something bar-related"
} }
:: .. code-block:: none
$ lua script.lua baz $ lua script.lua baz
:: .. code-block:: none
Usage: script.lua [-h] <choice> Usage: script.lua [-h] <choice>
@@ -104,11 +126,11 @@ Initial value to be stored at target index in the result table can be set using
end end
end):init({"foo", "bar"}) end):init({"foo", "bar"})
parser:flag("--no-exceptions"):action(function() parser:flag("--no-exceptions"):action(function(args)
args.exceptions = {} args.exceptions = {}
end) end)
:: .. code-block:: none
$ lua script.lua --exceptions x y --exceptions z t $ lua script.lua --exceptions x y --exceptions z t
@@ -125,7 +147,7 @@ Initial value to be stored at target index in the result table can be set using
} }
} }
:: .. code-block:: none
$ lua script.lua --exceptions x y --no-exceptions $ lua script.lua --exceptions x y --no-exceptions
@@ -145,11 +167,11 @@ Actions can also be used when a flag needs to print some message and exit withou
os.exit(0) os.exit(0)
end) end)
:: .. code-block:: none
$ lua script.lua -v $ lua script.lua -v
:: .. code-block:: none
script v1.0.0 script v1.0.0
@@ -179,7 +201,7 @@ Examples using ``store_false`` and ``concat`` actions:
parser:flag("--rain", "Enable rain", false) parser:flag("--rain", "Enable rain", false)
parser:option("--exceptions"):args("*"):action("concat"):init({"foo", "bar"}) parser:option("--exceptions"):args("*"):action("concat"):init({"foo", "bar"})
:: .. code-block:: none
$ lua script.lua $ lua script.lua
@@ -189,7 +211,7 @@ Examples using ``store_false`` and ``concat`` actions:
rain = false rain = false
} }
:: .. code-block:: none
$ lua script.lua --candy $ lua script.lua --candy
@@ -200,7 +222,7 @@ Examples using ``store_false`` and ``concat`` actions:
rain = false rain = false
} }
:: .. code-block:: none
$ lua script.lua --no-candy --rain $ lua script.lua --no-candy --rain
@@ -211,7 +233,7 @@ Examples using ``store_false`` and ``concat`` actions:
rain = true rain = true
} }
:: .. code-block:: none
$ lua script.lua --exceptions x y --exceptions z t $ lua script.lua --exceptions x y --exceptions z t
@@ -246,11 +268,11 @@ Actions for parsers and commands are simply callbacks invoked after parsing, wit
print("Callbacks are fun!") print("Callbacks are fun!")
end) end)
:: .. code-block:: none
$ lua script.lua install $ lua script.lua install
:: .. code-block:: none
Running install Running install
Callbacks are fun! Callbacks are fun!

View File

@@ -12,7 +12,7 @@ Commands can be added using ``:command(name, description, epilog)`` method. Just
If a command it used, ``true`` is stored in the corresponding field of the result table. If a command it used, ``true`` is stored in the corresponding field of the result table.
:: .. code-block:: none
$ lua script.lua install $ lua script.lua install
@@ -24,11 +24,11 @@ If a command it used, ``true`` is stored in the corresponding field of the resul
A typo will result in an appropriate error message. A typo will result in an appropriate error message.
:: .. code-block:: none
$ lua script.lua instal $ lua script.lua instal
:: .. code-block:: none
Usage: script.lua [-h] <command> ... Usage: script.lua [-h] <command> ...
@@ -47,7 +47,7 @@ Use ``command_target`` property of the parser to store the name of used command
parser:command("install") parser:command("install")
parser:command("remove") parser:command("remove")
:: .. code-block:: none
$ lua script.lua install $ lua script.lua install
@@ -70,7 +70,7 @@ The Command class is a subclass of the Parser class, so all the Parser's methods
install:argument "rock" install:argument "rock"
install:option "-f --from" install:option "-f --from"
:: .. code-block:: none
$ lua script.lua install foo --from=bar $ lua script.lua install foo --from=bar
@@ -85,21 +85,21 @@ The Command class is a subclass of the Parser class, so all the Parser's methods
Commands have their own usage and help messages. Commands have their own usage and help messages.
:: .. code-block:: none
$ lua script.lua install $ lua script.lua install
:: .. code-block:: none
Usage: script.lua install [-f <from>] [-h] <rock> Usage: script.lua install [-f <from>] [-h] <rock>
Error: too few arguments Error: too few arguments
:: .. code-block:: none
$ lua script.lua install --help $ lua script.lua install --help
:: .. code-block:: none
Usage: script.lua install [-f <from>] [-h] <rock> Usage: script.lua install [-f <from>] [-h] <rock>
@@ -122,11 +122,11 @@ By default, if a parser has commands, using one of them is obligatory.
local parser = argparse() local parser = argparse()
parser:command "install" parser:command "install"
:: .. code-block:: none
$ lua script.lua $ lua script.lua
:: .. code-block:: none
Usage: script.lua [-h] <command> ... Usage: script.lua [-h] <command> ...

View File

@@ -12,7 +12,7 @@ For elements such as arguments and options, if ``default`` property is set to a
:description "Output file." :description "Output file."
:default "a.out" :default "a.out"
:: .. code-block:: none
$ lua script.lua $ lua script.lua
@@ -24,11 +24,11 @@ For elements such as arguments and options, if ``default`` property is set to a
The existence of a default value is reflected in help message, unless ``show_default`` property is set to ``false``. The existence of a default value is reflected in help message, unless ``show_default`` property is set to ``false``.
:: .. code-block:: none
$ lua script.lua --help $ lua script.lua --help
:: .. code-block:: none
Usage: script.lua [-o <output>] [-h] Usage: script.lua [-o <output>] [-h]
@@ -39,11 +39,11 @@ The existence of a default value is reflected in help message, unless ``show_def
Note that invocation without required arguments is still an error. Note that invocation without required arguments is still an error.
:: .. code-block:: none
$ lua script.lua -o $ lua script.lua -o
:: .. code-block:: none
Usage: script.lua [-o <output>] [-h] Usage: script.lua [-o <output>] [-h]
@@ -54,7 +54,8 @@ Default mode
``defmode`` property regulates how argparse should use the default value of an element. ``defmode`` property regulates how argparse should use the default value of an element.
If ``defmode`` contains ``u`` (for unused), the default value will be automatically passed to the element if it was not invoked at all. This is the default behavior. By default, or if ``defmode`` contains ``u`` (for unused), the default value will be automatically passed to the element if it was not invoked at all.
It will be passed minimal required of times, so that if the element is allowed to consume no arguments (e.g. using ``:args "?"``), the default value is ignored.
If ``defmode`` contains ``a`` (for argument), the default value will be automatically passed to the element if not enough arguments were passed, or not enough invocations were made. If ``defmode`` contains ``a`` (for argument), the default value will be automatically passed to the element if not enough arguments were passed, or not enough invocations were made.
@@ -69,11 +70,11 @@ Consider the difference:
:default "password" :default "password"
:defmode "arg" :defmode "arg"
:: .. code-block:: none
$ lua script.lua -h $ lua script.lua -h
:: .. code-block:: none
Usage: script.lua [-o <o>] [-p [<p>]] [-h] Usage: script.lua [-o <o>] [-p [<p>]] [-h]
@@ -82,7 +83,7 @@ Consider the difference:
-p [<p>] default: password -p [<p>] default: password
-h, --help Show this help message and exit. -h, --help Show this help message and exit.
:: .. code-block:: none
$ lua script.lua $ lua script.lua
@@ -92,7 +93,7 @@ Consider the difference:
o = "a.out" o = "a.out"
} }
:: .. code-block:: none
$ lua script.lua -p $ lua script.lua -p
@@ -104,11 +105,11 @@ Consider the difference:
p = "password" p = "password"
} }
:: .. code-block:: none
$ lua script.lua -o $ lua script.lua -o
:: .. code-block:: none
Usage: script.lua [-o <o>] [-p [<p>]] [-h] Usage: script.lua [-o <o>] [-p [<p>]] [-h]

View File

@@ -12,6 +12,7 @@ Contents:
commands commands
defaults defaults
callbacks callbacks
messages
misc misc
This is a tutorial for `argparse <https://github.com/mpeterv/argparse>`_, a feature-rich command line parser for Lua. This is a tutorial for `argparse <https://github.com/mpeterv/argparse>`_, a feature-rich command line parser for Lua.

266
docsrc/messages.rst Normal file
View File

@@ -0,0 +1,266 @@
Configuring help and usage messages
===================================
The usage and help messages of parsers and commands can be generated on demand using ``:get_usage()`` and ``:get_help()`` methods, and overridden using ``help`` and ``usage`` properties.
When using the autogenerated usage and help messages, there are several ways to adjust them.
Hiding arguments, options, and commands from messages
-----------------------------------------------------
If ``hidden`` property for an argument, an option or a command is set to ``true``,
it is not included into help and usage messages, but otherwise works normally.
.. code-block:: lua
:linenos:
parser:option "--normal-option"
parser:option "--deprecated-option"
:hidden(true)
.. code-block:: none
$ lua script.lua --help
.. code-block:: none
Usage: script.lua [--normal-option <normal_option>] [-h]
Options:
--normal-option <normal_option>
-h, --help Show this help message and exit.
.. code-block:: none
$ lua script.lua --deprecated-option value
.. code-block:: lua
{
deprecated_option = "value"
}
Setting argument placeholder
----------------------------
For options and arguments, ``argname`` property controls the placeholder for the argument in the usage message.
.. code-block:: lua
:linenos:
parser:option "-f" "--from"
:argname "<server>"
.. code-block:: none
$ lua script.lua --help
.. code-block:: none
Usage: script.lua [-f <server>] [-h]
Options:
-f <server>, --from <server>
-h, --help Show this help message and exit.
``argname`` can be an array of placeholders.
.. code-block:: lua
:linenos:
parser:option "--pair"
:args(2)
:argname {"<key>", "<value>"}
.. code-block:: none
$ lua script.lua --help
.. code-block:: none
Usage: script.lua [--pair <key> <value>] [-h]
Options:
--pair <key> <value>
-h, --help Show this help message and exit.
Grouping elements
-----------------
``:group(name, ...)`` method of parsers and commands puts passed arguments, options, and commands into
a named group with its own section in the help message. Elements outside any groups are put into a default section.
.. code-block:: lua
:linenos:
parser:group("Configuring output format",
parser:flag "-v --verbose",
parser:flag "--use-colors",
parser:option "--encoding"
)
parser:group("Configuring processing",
parser:option "--compression-level",
parser:flag "--skip-broken-chunks"
)
parser:flag "--version"
:action(function() print("script.lua 1.0.0") os.exit(0) end)
.. code-block:: none
$ lua script.lua --help
.. code-block:: none
Usage: script.lua [-v] [--use-colors] [--encoding <encoding>]
[--compression-level <compression_level>]
[--skip-broken-chunks] [--version] [-h]
Configuring output format:
-v, --verbose
--use-colors
--encoding <encoding>
Configuring processing:
--compression-level <compression_level>
--skip-broken-chunks
Other options:
--version
-h, --help Show this help message and exit.
Help message line wrapping
--------------------------
If ``help_max_width`` property of a parser or a command is set, when generating its help message, argparse will automatically
wrap lines, attempting to fit into given number of columns. This includes wrapping lines in parser description and epilog
and descriptions of arguments, options, and commands.
Line wrapping preserves existing line endings and only splits overly long input lines.
When breaking a long line, it replicates indentation of the line in the continuation lines.
Additionally, if the first non-space token in a line is ``*``, ``+``, or ``-``, the line is considered a list item,
and the continuation lines are aligned with the first word after the list item marker.
.. code-block:: lua
:linenos:
parser:help_max_width(80)
parser:option "-f --foo"
:description("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " ..
"incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation " ..
"ullamco laboris nisi ut aliquip ex ea commodo consequat.\n" ..
"The next paragraph is indented:\n" ..
" Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. " ..
"Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
parser:option "-b --bar"
:description("Here is a list:\n"..
"* Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor...\n" ..
"* Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip...\n" ..
"* Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.")
.. code-block:: none
$ lua script.lua --help
.. code-block:: none
Usage: script.lua [-f <foo>] [-b <bar>] [-h]
Options:
-f <foo>, Lorem ipsum dolor sit amet, consectetur adipiscing
--foo <foo> elit, sed do eiusmod tempor incididunt ut labore et
dolore magna aliqua. Ut enim ad minim veniam, quis
nostrud exercitation ullamco laboris nisi ut aliquip ex
ea commodo consequat.
The next paragraph is indented:
Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt
in culpa qui officia deserunt mollit anim id est
laborum.
-b <bar>, Here is a list:
--bar <bar> * Lorem ipsum dolor sit amet, consectetur adipiscing
elit, sed do eiusmod tempor...
* Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip...
* Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur.
-h, --help Show this help message and exit.
``help_max_width`` property is inherited by commands.
Configuring help and usage message layout
-----------------------------------------
Several other parser and command properties can be used to tweak help and usage message format.
Like ``help_max_width``, all of them are inherited by commands when set on the parser or a parent command.
``usage_max_width`` property sets maximum width of the usage string. Default is ``70``.
``usage_margin`` property sets margin width used when line wrapping long usage strings. Default is ``7``.
.. code-block:: lua
:linenos:
parser:usage_max_width(50)
:usage_margin(#"Usage: script.lua ")
parser:option "--foo"
parser:option "--bar"
parser:option "--baz"
parser:option "--qux"
print(parser:get_usage())
.. code-block:: none
$ lua script.lua
.. code-block:: none
Usage: script.lua [--foo <foo>] [--bar <bar>]
[--baz <baz>] [--qux <qux>] [-h]
Help message for a group of arguments, options, or commands is organized into two columns, with usage
template on the left side and descriptions on the right side.
``help_usage_margin`` property sets horizontal offset for the first column (``3`` by default).
``help_description_margin`` property sets horizontal offset for the second column (``25`` by default).
``help_vertical_space`` property sets number of extra empty lines to put between descriptions for different elements
within a group (``0`` by default).
.. code-block:: lua
:linenos:
parser:help_usage_margin(2)
:help_description_margin(17)
:help_vertical_space(1)
parser:option("--foo", "Set foo.")
parser:option("--bar", "Set bar.")
parser:option("--baz", "Set baz.")
parser:option("--qux", "Set qux.")
.. code-block:: none
$ lua script.lua --help
.. code-block:: none
Usage: script.lua [--foo <foo>] [--bar <bar>] [--baz <baz>]
[--qux <qux>] [-h]
Options:
--foo <foo> Set foo.
--bar <bar> Set bar.
--baz <baz> Set baz.
--qux <qux> Set qux.
-h, --help Show this help message and exit.

View File

@@ -1,11 +1,6 @@
Miscellaneous Miscellaneous
============= =============
Generating and overwriting help and usage messages
--------------------------------------------------
The usage and help messages of parsers and commands can be generated on demand using ``:get_usage()`` and ``:get_help()`` methods, and overridden using ``help`` and ``usage`` properties.
Overwriting default help option Overwriting default help option
------------------------------- -------------------------------
@@ -17,61 +12,17 @@ If the property ``add_help`` of a parser is set to ``false``, no help option wil
local parser = argparse() local parser = argparse()
:add_help "/?" :add_help "/?"
:: .. code-block:: none
$ lua script.lua /? $ lua script.lua /?
:: .. code-block:: none
Usage: script.lua [/?] Usage: script.lua [/?]
Options: Options:
/? Show this help message and exit. /? Show this help message and exit.
Setting argument placeholder
----------------------------
For options and arguments, ``argname`` property controls the placeholder for the argument in the usage message.
.. code-block:: lua
:linenos:
parser:option "-f" "--from"
:argname "<server>"
::
$ lua script.lua --help
::
Usage: script.lua [-f <server>] [-h]
Options:
-f <server>, --from <server>
-h, --help Show this help message and exit.
``argname`` can be an array of placeholders.
.. code-block:: lua
:linenos:
parser:option "--pair"
:args(2)
:argname {"<key>", "<value>"}
::
$ lua script.lua --help
::
Usage: script.lua [--pair <key> <value>] [-h]
Options:
--pair <key> <value>
-h, --help Show this help message and exit.
Disabling option handling Disabling option handling
------------------------- -------------------------
@@ -86,7 +37,7 @@ When ``handle_options`` property of a parser or a command is set to ``false``, a
parser:option "-f" "--foo" parser:option "-f" "--foo"
:args "*" :args "*"
:: .. code-block:: none
$ lua script.lua bar -f --foo bar $ lua script.lua bar -f --foo bar
@@ -106,7 +57,7 @@ By default, if an option is invoked too many times, latest invocations overwrite
parser:option "-o --output" parser:option "-o --output"
:: .. code-block:: none
$ lua script.lua -oFOO -oBAR $ lua script.lua -oFOO -oBAR
@@ -124,11 +75,11 @@ Set ``overwrite`` property to ``false`` to prohibit this behavior.
parser:option "-o --output" parser:option "-o --output"
:overwrite(false) :overwrite(false)
:: .. code-block:: none
$ lua script.lua -oFOO -oBAR $ lua script.lua -oFOO -oBAR
:: .. code-block:: none
Usage: script.lua [-o <output>] [-h] Usage: script.lua [-o <output>] [-h]
@@ -168,16 +119,22 @@ Property Type
Other properties: Other properties:
=================== ========================== =========================== ==========================
Property Type Property Type
=================== ========================== =========================== ==========================
``usage`` String ``usage`` String
``help`` String ``help`` String
``require_command`` Boolean ``require_command`` Boolean
``handle_options`` Boolean ``handle_options`` Boolean
``add_help`` Boolean or string or table ``add_help`` Boolean or string or table
``command_target`` String ``command_target`` String
=================== ========================== ``usage_max_width`` Number
``usage_margin`` Number
``help_max_width`` Number
``help_usage_margin`` Number
``help_description_margin`` Number
``help_vertical_space`` Number
=========================== ==========================
Command properties Command properties
^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
@@ -194,9 +151,9 @@ Property Type
Other properties: Other properties:
=================== ========================== =========================== ==========================
Property Type Property Type
=================== ========================== =========================== ==========================
``target`` String ``target`` String
``usage`` String ``usage`` String
``help`` String ``help`` String
@@ -205,7 +162,14 @@ Property Type
``action`` Function ``action`` Function
``add_help`` Boolean or string or table ``add_help`` Boolean or string or table
``command_target`` String ``command_target`` String
=================== ========================== ``hidden`` Boolean
``usage_max_width`` Number
``usage_margin`` Number
``help_max_width`` Number
``help_usage_margin`` Number
``help_description_margin`` Number
``help_vertical_space`` Number
=========================== ==========================
Argument properties Argument properties
^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^
@@ -233,6 +197,7 @@ Property Type
``argname`` String or table ``argname`` String or table
``action`` Function or string ``action`` Function or string
``init`` Any ``init`` Any
``hidden`` Boolean
=================== =============== =================== ===============
Option and flag properties Option and flag properties
@@ -263,4 +228,5 @@ Property Type
``argname`` String or table ``argname`` String or table
``action`` Function or string ``action`` Function or string
``init`` Any ``init`` Any
``hidden`` Boolean
=================== ================== =================== ==================

View File

@@ -1,11 +1,17 @@
Mutually exclusive groups Mutually exclusive groups
========================= =========================
A group of options can be marked as mutually exclusive using ``:mutex(option, ...)`` method of the Parser class. A group of arguments and options can be marked as mutually exclusive using ``:mutex(argument_or_option, ...)`` method of the Parser class.
.. code-block:: lua .. code-block:: lua
:linenos: :linenos:
parser:mutex(
parser:argument "input"
:args "?",
parser:flag "--process-stdin"
)
parser:mutex( parser:mutex(
parser:flag "-q --quiet", parser:flag "-q --quiet",
parser:flag "-v --verbose" parser:flag "-v --verbose"
@@ -13,12 +19,22 @@ A group of options can be marked as mutually exclusive using ``:mutex(option, ..
If more than one element of a mutually exclusive group is used, an error is raised. If more than one element of a mutually exclusive group is used, an error is raised.
:: .. code-block:: none
$ lua script.lua -qv $ lua script.lua -qv
:: .. code-block:: none
Usage: script.lua ([-q] | [-v]) [-h] Usage: script.lua ([-q] | [-v]) [-h] ([<input>] | [--process-stdin])
Error: option '-v' can not be used together with option '-q' Error: option '-v' can not be used together with option '-q'
.. code-block:: none
$ lua script.lua file --process-stdin
.. code-block:: none
Usage: script.lua ([-q] | [-v]) [-h] ([<input>] | [--process-stdin])
Error: option '--process-stdin' can not be used together with argument 'input'

View File

@@ -10,7 +10,7 @@ Options can be added using ``:option(name, description, default, convert, args,
parser:option "-f" "--from" parser:option "-f" "--from"
parser:option "-f --from" parser:option "-f --from"
:: .. code-block:: none
$ lua script.lua --from there $ lua script.lua --from there
$ lua script.lua --from=there $ lua script.lua --from=there
@@ -45,7 +45,7 @@ Flags are almost identical to options, except that they don't take an argument b
parser:flag("-q --quiet") parser:flag("-q --quiet")
:: .. code-block:: none
$ lua script.lua -q $ lua script.lua -q
@@ -73,7 +73,7 @@ Just as arguments, options can be configured to take several command line argume
parser:option "--optional" parser:option "--optional"
:args "?" :args "?"
:: .. code-block:: none
$ lua script.lua --pair foo bar $ lua script.lua --pair foo bar
@@ -83,7 +83,7 @@ Just as arguments, options can be configured to take several command line argume
pair = {"foo", "bar"} pair = {"foo", "bar"}
} }
:: .. code-block:: none
$ lua script.lua --pair foo bar --optional $ lua script.lua --pair foo bar --optional
@@ -94,7 +94,7 @@ Just as arguments, options can be configured to take several command line argume
optional = {} optional = {}
} }
:: .. code-block:: none
$ lua script.lua --optional=baz $ lua script.lua --optional=baz
@@ -118,7 +118,7 @@ For options, it is possible to control how many times they can be used. argparse
parser:option("-e --exclude") parser:option("-e --exclude")
:count "*" :count "*"
:: .. code-block:: none
$ lua script.lua -eFOO -eBAR $ lua script.lua -eFOO -eBAR
@@ -139,7 +139,7 @@ As a special case, if an option can be used more than once and it consumes no ar
:count "0-2" :count "0-2"
:target "verbosity" :target "verbosity"
:: .. code-block:: none
$ lua script.lua -vv $ lua script.lua -vv

View File

@@ -15,26 +15,25 @@ The ``argparse`` module is a function which, when called, creates an instance of
Parsing command line arguments Parsing command line arguments
------------------------------ ------------------------------
``:parse([args])`` method of the Parser class returns a table with processed data from the command line or ``args`` array. ``:parse([argv])`` method of the Parser class returns a table with processed data from the command line or ``argv`` array.
.. code-block:: lua .. code-block:: lua
:linenos: :linenos:
local args = parser:parse() local args = parser:parse()
print(args) -- Assuming print is patched to handle tables nicely.
When executed, this script prints ``{}`` because the parser is empty and no command line arguments were supplied. After this is executed with ``lua script.lua``, ``args`` is an empty table because the parser is empty and no command line arguments were supplied.
Error handling Error handling
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
If the provided command line arguments are not recognized by the parser, it will print an error message and call ``os.exit(1)``. If the provided command line arguments are not recognized by the parser, it will print an error message and call ``os.exit(1)``.
:: .. code-block:: none
$ lua script.lua foo $ lua script.lua foo
:: .. code-block:: none
Usage: script.lua [-h] Usage: script.lua [-h]
@@ -49,7 +48,7 @@ An error can raised manually using ``:error()`` method.
parser:error("manual argument validation failed") parser:error("manual argument validation failed")
:: .. code-block:: none
Usage: script.lua [-h] Usage: script.lua [-h]
@@ -62,11 +61,11 @@ As the automatically generated usage message states, there is a help option ``-h
When a help option is used, parser will print a help message and call ``os.exit(0)``. When a help option is used, parser will print a help message and call ``os.exit(0)``.
:: .. code-block:: none
$ lua script.lua -h $ lua script.lua -h
:: .. code-block:: none
Usage: script.lua [-h] Usage: script.lua [-h]
@@ -78,11 +77,11 @@ Typo autocorrection
When an option is not recognized by the parser, but there is an option with a similar name, a suggestion is automatically added to the error message. When an option is not recognized by the parser, but there is an option with a similar name, a suggestion is automatically added to the error message.
:: .. code-block:: none
$ lua script.lua --hepl $ lua script.lua --hepl
:: .. code-block:: none
Usage: script.lua [-h] Usage: script.lua [-h]