【问题标题】:How can I use scopt in Scala to get all of the remaining arguments?如何在 Scala 中使用 scopt 来获取所有剩余的参数?
【发布时间】:2019-09-20 22:52:04
【问题描述】:

我正在使用 scopt 库:https://github.com/scopt/scopt

如果我事先知道选项名称,我可以定义一个带有选项名称的案例类。如果我不知道用户将通过的选项的名称怎么办?我有什么办法可以在字典或其他东西中捕获这些选项值吗?

谢谢!

【问题讨论】:

    标签: scala command-line-interface scopt


    【解决方案1】:

    像这样试试opt[Map[String,String]]

    case class Config(args: Map[String, String] = Map())
    
    object Hello extends App {
      val parser = new scopt.OptionParser[Config]("scopt") {
        head("scopt", "3.x")
        opt[Map[String,String]]("args").valueName("k1=v1,k2=v2...").action( (x, c) =>
          c.copy(args = x) ).text("other arguments")
      }
    
      parser.parse(args, Config()) match {
        case Some(config) => println(config)
        case None =>
        // arguments are bad, error message will have been displayed
      }
    }
    

    使用

    执行
    run --args key1=val1,key2=val2
    

    输出

    Config(Map(key1 -> val1, key2 -> val2))
    

    【讨论】:

    • 我希望在不将语法更改为键值映射的情况下捕获传入的任何其他可选参数。这可能吗?
    猜你喜欢
    • 1970-01-01
    • 2014-05-16
    • 2016-03-31
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    相关资源
    最近更新 更多