繁体   English   中英

如何使用 nim 的 `argparse` 获得可变数量的参数

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

我今天开始学习 nim,所以欢迎任何形式的建议。

我尝试使用argparse ,认为它与 Python 库的相似性会让我的生活变得轻松。

我想要一个具有此接口的应用程序:

tool [options] File1 File2 ... FileN

我的解析器 object 就像:


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

我正在寻找类似nargs="+"的东西,但据我了解,integer 是预期的,我不知道如何指定任意数量的输入。

谢谢!

PS

  • 我用来实验的工具在这里

您可以通过添加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())

如果你想,至少说一个 FASTA,但更多可能,这是语法:

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

现在par.firstFile包含带有第一个文件的字符串,而par.otherFiles包含带有 rest 的seq[string]


请记住,Nim 有自己的命令行解析器,起初看起来有点复杂,但对于简单的事情它可能很有用:

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())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM