21

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.

4 Answers 4

28

Here is an example that prints the number of arguments and the first argument:

import std/os

echo paramCount(), " ", paramStr(1)
9

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:

0

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.

0

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"]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.