JanetDocsSourcePlaygroundTutorialsI'm Feeling luckyCommunityGitHub sign in

argparse/argparse

argparse


    function
    /usr/local/lib/janet/argparse.janet on line 15, column 1

    (argparse description &keys options)

    Parse (dyn :args) according to options. If the arguments are 
    incorrect, will return nil and print usage information. Each option 
    is a table or struct that specifies a flag or option for the 
    script. The name of the option should be a string, specified via 
    (argparse/argparse "..." op1-name {...} op2-name {...} ...). A help 
    option and usage text is automatically generated for you.

    The keys in each option table are as follows:

    	:kind - What kind of option is this? One of :flag, :multi, 
    :option, or :accumulate. A flag can either be on or off, a multi is 
    a flag that can be provided multiple times, each time adding 1 to a 
    returned integer, an option is a key that will be set in the 
    returned table, and accumulate means an option can be specified 0 
    or more times, each time appending a value to an array. 	:short - 
    Single letter for shorthand access. 	:help - Help text for the 
    option, explaining what it is. 	:default - Default value for the 
    option. 	:required - Whether or not an option is required. 
    	:short-circuit - Whether or not to stop parsing and fail if this 
    option is hit. 	:action - A function that will be invoked when the 
    option is parsed.

    There is also a special option :default that will be invoked on 
    arguments that do not start with a -- or -. Use this option to 
    collect unnamed arguments to your script.

    After `--`, every argument is treated as an unnamed argument.

    Once parsed, values are accessible in the returned table by the 
    name of the option. For example (result "verbose") will check if 
    the verbose flag is enabled.


1 exampleSign in to add an example
Loading...
# Expanding the example from https://janetdocs.org/core-api/stdin
# We use argparse to provide automatically add flags
# --help comes for free, try it!

(import spork/argparse)

(defn main [&]
  (let [opts (argparse/argparse "Sum numbers from files, stdin or data."
              "multiply" {:kind :option :short "m" :default "1" :map scan-number :help "Multiply the result"}
              "verbose"  {:kind :flag :help "Print the input first"}
              :default   {:kind :accumulate})

        _ (unless opts (os/exit 0)) # lest it crash on help etc.
        args (or (opts :default) []) # give empty? empty array of :default is nil
        data (cond (empty? args) (file/read stdin :all)
                   (os/stat (first args)) (slurp (first args))
                   (string/join args " "))
        total (* (opts "multiply") (sum (flatten (parse-all data))))]

    (if (opts "verbose") (print "Data: " data))
    (print total)))
veqqqPlayground