all

解析命令行参数的最佳方法?

发布于 2022-05-26 22:56:00

在 Scala 中解析命令行参数的最佳方法是什么?我个人更喜欢不需要外部 jar 的轻量级产品。

关注者
0
被浏览
20
1 个回答
  • 面试哥
    面试哥 2022-05-26
    为面试而生,有面试问题,就找面试哥。

    观察/观察

    val parser = new scopt.OptionParser[Config]("scopt") {
      head("scopt", "3.x")
    
      opt[Int]('f', "foo") action { (x, c) =>
        c.copy(foo = x) } text("foo is an integer property")
    
      opt[File]('o', "out") required() valueName("<file>") action { (x, c) =>
        c.copy(out = x) } text("out is a required file property")
    
      opt[(String, Int)]("max") action { case ((k, v), c) =>
        c.copy(libName = k, maxCount = v) } validate { x =>
        if (x._2 > 0) success
        else failure("Value <max> must be >0") 
      } keyValueName("<libname>", "<max>") text("maximum count for <libname>")
    
      opt[Unit]("verbose") action { (_, c) =>
        c.copy(verbose = true) } text("verbose is a flag")
    
      note("some notes.\n")
    
      help("help") text("prints this usage text")
    
      arg[File]("<file>...") unbounded() optional() action { (x, c) =>
        c.copy(files = c.files :+ x) } text("optional unbounded args")
    
      cmd("update") action { (_, c) =>
        c.copy(mode = "update") } text("update is a command.") children(
        opt[Unit]("not-keepalive") abbr("nk") action { (_, c) =>
          c.copy(keepalive = false) } text("disable keepalive"),
        opt[Boolean]("xyz") action { (x, c) =>
          c.copy(xyz = x) } text("xyz is a boolean property")
      )
    }
    // parser.parse returns Option[C]
    parser.parse(args, Config()) map { config =>
      // do stuff
    } getOrElse {
      // arguments are bad, usage message will have been displayed
    }
    

    以上生成以下使用文本:

    scopt 3.x
    Usage: scopt [update] [options] [<file>...]
    
      -f <value> | --foo <value>
            foo is an integer property
      -o <file> | --out <file>
            out is a required file property
      --max:<libname>=<max>
            maximum count for <libname>
      --verbose
            verbose is a flag
    some notes.
    
      --help
            prints this usage text
      <file>...
            optional unbounded args
    
    Command: update
    update is a command.
    
      -nk | --not-keepalive
            disable keepalive    
      --xyz <value>
            xyz is a boolean property
    

    这是我目前使用的。清洁使用没有太多的行李。(免责声明:我现在维护这个项目)



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看