Merge pull request #1175 from Kodiologist/argparse

Add an example of using argparse with defmain
This commit is contained in:
Ryan Gonzalez 2016-12-13 11:29:42 -06:00 committed by GitHub
commit bc436d0fcd

View File

@ -624,7 +624,7 @@ is the equivalent of::
if __name__ == "__main__":
import sys
retval = main(*sys.arg)
retval = main(*sys.argv)
if isinstance(retval, int):
sys.exit(retval)
@ -632,12 +632,28 @@ is the equivalent of::
Note that as you can see above, if you return an integer from this
function, this will be used as the exit status for your script.
(Python defaults to exit status 0 otherwise, which means everything's
okay!)
okay!) Since ``(sys.exit 0)`` is not run explicitly in the case of a
non-integer return from ``defmain``, it's a good idea to put ``(defmain)``
as the last piece of code in your file.
(Since ``(sys.exit 0)`` is not run explicitly in the case of a non-integer
return from ``defmain``, it's a good idea to put ``(defmain)`` as the last
piece of code in your file.)
If you want fancy command-line arguments, you can use the standard Python
module ``argparse`` in the usual way:
.. code-block:: clj
(import argparse)
(defmain [&rest _]
(setv parser (argparse.ArgumentParser))
(.add-argument parser "STRING"
:help "string to replicate")
(.add-argument parser "-n" :type int :default 3
:help "number of copies")
(setv args (parser.parse_args))
(print (* args.STRING args.n))
0)
.. _defmacro: