From 28b9874efd237e8c67b0220594650f7b14d01b94 Mon Sep 17 00:00:00 2001 From: Kodi Arfer Date: Tue, 13 Dec 2016 08:57:31 -0800 Subject: [PATCH] Add an example of using argparse with defmain Closes #1091. --- docs/language/api.rst | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/docs/language/api.rst b/docs/language/api.rst index 78cd1c9..1c5a2ec 100644 --- a/docs/language/api.rst +++ b/docs/language/api.rst @@ -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: