How to get access to command-line arguments in Nim?
Asked Answered
N

4

22

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.

Nabila answered 12/4, 2017 at 11:29 Comment(0)
K
28

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

import std/os

echo paramCount(), " ", paramStr(1)
Kyrakyriako answered 12/4, 2017 at 12:24 Comment(0)
H
10

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:

Horripilate answered 10/10, 2019 at 13:31 Comment(0)
G
1

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"]
Gulch answered 23/11, 2022 at 22:12 Comment(0)
H
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.

Hic answered 7/8, 2022 at 4:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.