2017-07-03 154 views
2

我想用OCaml中的參數解析命令行選項。OCaml - 使用參數解析帶參數的命令行選項

標準庫的模塊Arg似乎做我需要的一切,並有一些教程解釋如何使用此模塊。

我的問題是,當一個選項的參數丟失時,它們似乎都共享相同的奇怪行爲。例如,從與this example./a.out -d執行程序產生以下輸出:

./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 

我無法找出爲什麼錯誤/用法消息被打印三次。這也發生在我在網上找到的所有其他代碼示例中。這是Arg模塊中的問題,還是在這些示例中以某種方式未正確使用?

+0

你使用什麼版本的編譯器? (我已經設法在4.04.2下現在重現) – RichouHunter

+0

使用OCaml 4.02.3運行不會導致此行爲。我建議你檢查一下[OCaml bug-tracker](https://caml.inria.fr/mantis/view_all_bug_page.php),看看這個問題是否曾經被報告過。 :) – RichouHunter

回答

3

我已經成功地重現了OCaml 4.04.2的錯誤,但沒有使用4.02.3,所以看起來似乎有某種迴歸正在進行。

所以,你可以做的一件事是堅持OCaml的舊版本,但我不會建議。您可以使用替代標準庫,例如Jane Street的Core。它有一個名爲Command的模塊,它允許您編寫與您嘗試運行的命令行界面相似的命令行界面。

該模塊的詳細教程可用here

作爲一個例子,這裏是使用從Command羅塞塔的CLI:

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 

EDIT:此錯誤已知的,並且is going to be fixed in OCaml 4.05

+0

我對opam並不是很有經驗,但似乎'opam install core'需要將包zarith降級到1.4.1。不幸的是,我的項目取決於zarith 1.5。像getopt或getopts這樣的其他命令行包似乎也取決於舊版本的zarith。 不過謝謝你的迴應。我想有多個版本的同一個軟件包會使一切變得更加複雜,這意味着我寧願等待OCaml 4.05。代替。 – tomatenbrei

+0

只是想一想:在嘗試安裝core之前是否運行過「opam update」? – RichouHunter

+0

不,但'opam update'遺憾地沒有改變zarith的所需版本。 – tomatenbrei