How can I access command line arguments in Nim?
The documentation shows only how to run the compiled Nim code with command line arguments
nim compile --run greetings.nim arg1 arg2
but I didn't find how to use their values in code.
How can I access command line arguments in Nim?
The documentation shows only how to run the compiled Nim code with command line arguments
nim compile --run greetings.nim arg1 arg2
but I didn't find how to use their values in code.
Here is an example that prints the number of arguments and the first argument:
import std/os
echo paramCount(), " ", paramStr(1)
Personally I find paramCount
and paramStr
a bit confusing to work with, because the paramCount
value differs from C conventions (see the document links).
Fortunately, there are additional convenient functions which do not require to be aware of the conventions:
commandLineParams
returns a seq
of only command line params.getAppFilename
returns the executable file name (what is argv[0]
in the C world).os.commandLineParams()
returns a sequence of command-line arguments provided to the program.
os.quoteShellCommand(<openArray[string]>)
takes a sequence of command-line arguments and turns it into a single string with quotes around items containing spaces, so the string can be parsed properly.
parseopt.initOptParser(<string>)
takes a full command-line string and parses it, returning an OptParser
object.
parseopt.getopt(<OptParser>)
is an iterator that yields parsed argument info.
You can combine them to parse a program's input arguments:
import std/[os, parseopt]
proc writeHelp() = discard
proc writeVersion() = discard
var positionalArgs = newSeq[string]()
var directories = newSeq[string]()
var optparser = initOptParser(quoteShellCommand(commandLineParams()))
for kind, key, val in optparser.getopt():
case kind
of cmdArgument:
positionalArgs.add(key)
of cmdLongOption, cmdShortOption:
case key
of "help", "h": writeHelp()
of "version", "v": writeVersion()
of "dir", "d":
directories.add(val)
of cmdEnd: assert(false) # cannot happen
echo "positionalArgs: ", positionalArgs
echo "directories: ", directories
Running this with nim c -r main.nim -d:foo --dir:bar dir1 dir2 dir3
prints:
positionalArgs: @["dir1", "dir2", "dir3"]
directories: @["foo", "bar"]
I have not checked when it was added, but the parseopt seems to me, the default and the best way for this.
commandLineParams
isn't available on Posix.
© 2022 - 2024 — McMap. All rights reserved.