POSIX command line argument processing
Posted: Fri Jul 22, 2011 9:19 am
I have made a module called "getopts". It doesn't use its own context. I don't think it needs to. If people can try it out, it does the following:
It parses command line options in the following forms:
Anything that is not an option, or an argument to an option, is just accumulated to a list. At the end of the option processing, this accumulated list is returned for your own custom processing.
There is just one possible glitch. I start the argument parsing at index position 2 of main-args. For my scripts, this works well.
As a bonus, the way it is set up, the "usage" function, automatically lists all the options that you have specified. Also, unlike in C, you don't call getopt repeatedly. The getopts function does it all in one pass. Here is an example of how to use it:
Example usage:
There is just one issue. If I pass an argument to newlisp, it changes the starting point for processing in main-args. I see no way to detect this.
See how it differs? Wouldn't it be better if there was an empty string there always, in index position 1, if there are no arguments passed to the newlisp interpreter?
It parses command line options in the following forms:
Code: Select all
-f filename
-ffilename (-f filename)
-avh (-a -v -h)
-avfboo (-a -v -f boo)
--long-option
--long-option with-argument
--long-option=with-argument (--long-option "with-argument")
-- (everything after -- is ignored)
There is just one possible glitch. I start the argument parsing at index position 2 of main-args. For my scripts, this works well.
As a bonus, the way it is set up, the "usage" function, automatically lists all the options that you have specified. Also, unlike in C, you don't call getopt repeatedly. The getopts function does it all in one pass. Here is an example of how to use it:
Code: Select all
(module "getopts.lsp")
(short-opt "v" (++ verbosity) nil "Increase verbosity")
(short-opt "q" (setq verbosity 0) nil "Quiet")
(short-opt "?" (usage) nil "Print this usage message")
(short-opt "h" (usage) nil "Print this usage message")
(short-opt "o" (setq output-file arg) "file" "Output file")
(long-opt "help" (usage) nil "Print this usage message")
(long-opt "quiet" (setq verbosity 0) nil "Quiet")
(long-opt "verbose" (++ verbosity) nil)
(long-opt "output" (setq output-file arg) "file" "Output file")
(println (getopts)) ; this shows the command line datum that weren't options
(println "Verbosity: " verbosity)
(println "Output To: " output-file)
(exit)
Code: Select all
$ ./test.lsp --output foo -obar -v --quiet -vv arg1 arg2
("arg1" "arg2")
Verbosity: 2
Output To: bar
Code: Select all
#!/usr/bin/newlisp
$ ./test.lsp foo bar
main-args: "/usr/bin/newlisp" "./test.lsp" "foo" "bar"
#!/usr/bin/newlisp -m 50 -s 1024
$ ./test.lsp foo bar
main-args: "/usr/bin/newlisp" "-m 50 -s 1024" "./test.lsp" "foo" "bar"