How to read command line arguments in Nim with examples?

This tutorial explains how to read command line arguments in NIm code

For example, You have hello.nim code, that you want to run the code by passing arguments separated by space.

nim compile --run hello.nim arguments

How to read command line arguments in NIM

Multiple ways to read command line arguments in Nim programming language

  • using the os commandLineParams procedure commandLineParams returns the Sequence of a string that passed to the command line

Here is an example

  proc commandLineParams(): seq[string] {.....}

Here is an example test.nim

import os
const args = commandLineParams()
echo args
echo typeOf(args)
echo args[0]
echo args[1]

On running program

nim compile --run hello.nim one two three

Output

@["one", "two", "three"]
seq[string]
one
two

Note: this procedure does not work on the POSIX system.

  • using os paramStr procedure

paramStr(index) always returns the only string at a time using an index.

It throws an IndexDefect if an invalid index.

paramStr(0) - returns the name of the file paramStr(1 to n) - returns the command line arguments, always starts with index=1

import os

let
  argument1 = paramStr(1)
  argument2 = paramStr(2)
  argument3 = paramStr(3)

Note: this procedure does not works on the POSIX system.

  • using parseopt module

You can also use parseopt module to read command line arguments which work in POSIX