How do I properly pass arguments via the command line to NIM?
I am using the following snippet to parse the command line arguments and store them in a table.
var args = initTable[string, string]()
for kind, key, val in getopt():
args.add(key,val)
However, it only works if I pass =
on the command line
./mytool -i=somefile.txt
In this case, args
there is {i: somefile.txt}
what I want (key: value pair).
But if I use ./mytool -i somefile.txt
, that args
is {somefile.txt: , i: }
, that is definitely not what I would expect (two keys and no values).
What is the correct way to parse arguments without using it =
?
Here's a printout of the view, key and val in two cases:
$ ./diceof -a=ACTGCTGTGTGCACAGTGTCACGTGT -b=ACTGCTGTGTGCACAGTGTCACGTGa
kind:cmdShortOption
key :a
val :ACTGCTGTGTGCACAGTGTCACGTGT
kind:cmdShortOption
key :b
val :ACTGCTGTGTGCACAGTGTCACGTGa
$ ./diceof -a ACTGCTGTGTGCACAGTGTCACGTGT -b ACTGCTGTGTGCACAGTGTCACGTGa
kind:cmdShortOption
key :a
val :
kind:cmdArgument
key :ACTGCTGTGTGCACAGTGTCACGTGT
val :
kind:cmdShortOption
key :b
val :
kind:cmdArgument
key :ACTGCTGTGTGCACAGTGTCACGTGa
val :
Of course I could check if it was found val
if not add the next one key
as the val
previous one. But I am looking for a more elegant solution.
source to share
Based on the documentation for parseopt2 and the discussion in the commandeer (see # 10), parseopt2 can only set values ββfor keys using =
or :
, other than that, I don't know if there is a "correct" way to parse parameter values.
The commander works with options, where key and value are separated by a space, checking if the next token is a cmdArgument argument and assigning a value.
var nextToken = cliTokens.pop()
if nextToken.kind == parseopt2.cmdArgument:
try:
assign(nextToken.key)
except ValueError:
exitWithErrorMessage(getCurrentExceptionMsg())
else:
cliTokens.add(nextToken)
source to share
argparse
seems to be the only Nim package that finally supports POSIX-style argument parsing and automatically generates application help (usage) text:
$ ./example -c=settings.cfg
Parsed opts: (config: "settings.cfg", help: false)
$ ./example -c settings.cfg
Parsed opts: (config: "settings.cfg", help: false)
$ ./example -h
example
Usage:
example [options]
Options:
-c, --config=CONFIG Configuration file
-h, --help Show this help
Parsed opts: (config: "", help: true)
Source:
import argparse
let p = newParser("example"):
option("-c", "--config", help="Configuration file")
echo("Parsed opts: ", p.parse(commandLineParams()))
source to share