20

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.

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Lucian Bredean
  • 803
  • 1
  • 10
  • 21

4 Answers4

27

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

import os

echo paramCount(), " ", paramStr(1)
Alex Boisvert
  • 2,850
  • 2
  • 19
  • 18
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:

bluenote10
  • 23,414
  • 14
  • 122
  • 178
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.

0xc0de
  • 8,028
  • 5
  • 49
  • 75
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"]
elijahr
  • 111
  • 7