how to have a variable number of parameters using `argparse` for nim

Viewed 267

I started today learning nim, so any kind of suggestion is welcome.

I tried using argparse thinking its similarity with Python's library would make my life easy.

I'd like to have an application with this interface:

tool [options] File1 File2 ... FileN

my parser object is like:


var p = newParser(prog):
  help("Dereplicate FASTA (and FASTQ) files, print dereplicated sorted by cluster size with ';size=NNN' decoration.")
  flag("-k", "--keep-name", help="Do not rename sequence, but use the first sequence name")
  flag("-i", "--ignore-size", help="Do not count 'size=INT;' annotations (they will be stripped in any case)")
  option("-m", "--min-size", help="Print clusters with size equal or bigger than INT sequences", default="0")
  option("-p", "--prefix", help = "Sequence name prefix", default = "seq")
  option("-s", "--separator", help = "Sequence name separator", default = ".")
  flag("-c", "--size-as-comment", help="Print cluster size as comment, not in sequence name")
  arg("inputfile", help="Input file")

I'm looking for something like nargs="+", but from what I understand an integer is expected, and I didn't get how to specify an arbitrary number of inputs.

Thanks!

PS:

  • The tool I'm using to experiment is here
1 Answers

You can do it by adding nargs=-1:

import os
import argparse

proc main(args: seq[string]) =
  var par = newParser("My Program"):
    option("--arg1")
    arg("files", nargs = -1)

  var opts = par.parse(args)
  echo "Opts: ", opts.arg1
  echo "Files: ", opts.files
  # For a command like `cmd --arg1=X file1 file2, echoes
  # Opts: X
  # Files: @[file1, file2]

when isMainModule:
  main(commandLineParams())

If you want, say at least one FASTA, but many more possible, this is the syntax:

var par = newParser("My Program"):
  option("--arg1")
  arg("firstFile")
  arg("otherFiles", nargs = -1)

Now par.firstFile contains a string with the first file, and par.otherFiles contains a seq[string] with the rest of them.


Remember that Nim has its own command line parser, that seems a bit complex at first, but for simple things it may be useful:

import os
import parseopt

proc main(args: seq[string]) =
  var par = initOptParser(args)
  var files: seq[string]

  for kind, key, val in args.getopt():
    case kind
    of cmdLongOption, cmdShortOption:
      # Here you deal with options like --option and -o
      discard
    of cmdArgument:
      # Here, any extra argument is added to the seq
      files.add key
    of cmdEnd: assert(false)

  echo files

when isMainModule:
  main(commandLineParams())
Related