簡體   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