OCaml - 使用 Arg 解析带有参数的命令行选项

OCaml - Parsing command-line options with arguments using Arg

我想用 OCaml 中的参数解析命令行选项。

标准库的模块 Arg 似乎可以满足我的所有需求,并且有一些教程解释了如何使用该模块。

我的问题是,当缺少选项的参数时,它们似乎都具有相同的奇怪行为。例如,使用 ./a.out -dthis example 执行程序会产生以下输出:

./a.out: option '-d' needs an argument.
usage: ./a.out [-b] [-s string] [-d int]
  -b : set somebool to true
  -s : what follows -s sets some string
  -d : some int parameter
  -help  Display this list of options
  --help  Display this list of options
./a.out: ./a.out: option '-d' needs an argument.
usage: ./a.out [-b] [-s string] [-d int]
  -b : set somebool to true
  -s : what follows -s sets some string
  -d : some int parameter
  -help  Display this list of options
  --help  Display this list of options
.
usage: ./a.out [-b] [-s string] [-d int]
  -b : set somebool to true
  -s : what follows -s sets some string
  -d : some int parameter
  -help  Display this list of options
  --help  Display this list of options

我无法找出 error/usage 消息被打印三次的原因。这也发生在我在网上找到的所有其他代码示例中。这是 Arg 模块中的问题还是这些示例中未正确使用它?

我已经成功地用 OCaml 4.04.2 重现了这个错误,但在 4.02.3 中没有重现,所以看起来那里正在进行某种回归。

所以,您可以做的一件事就是坚持使用旧版本的 OCaml,但我不建议这样做。

相反,您可以使用替代标准库,例如 Jane Street 的 Core。它有一个名为 Command 的模块,它允许您编写命令行界面,就像您尝试 运行.

此模块的详细教程可用here

例如,这是来自 Rosetta 的 CLI 使用 Command:

open Core

let spec =
  let open Command.Spec in
  empty
    +> flag "-b" (no_arg) ~doc:"Sets some flag"
    +> flag "-s" (optional_with_default "" string) ~doc:"STRING Some string parameter"
    +> flag "-d" (optional_with_default 0 int) ~doc:"INTEGER Some int parameter"

let command =
  Command.basic
    ~summary:"My awesome CLI"
    spec
    (fun some_flag some_string some_int () ->
       printf " %b '%s' %d\n" some_flag some_string some_int
    )

let () =
  Command.run command

编辑:这个错误是已知的并且is going to be fixed in OCaml 4.05