2017-09-11 43 views
1

在使用R創建命令行工具時,我決定使用docopt package。它適用於傳遞標誌,但我無法弄清楚如何傳遞兩個數字值。請參見下面的代碼:無法通過docopt包傳遞兩個數值參數

#! /usr/bin/Rscript 

'usage: ./test.R [-lr <low> -hr <high>] 

options: 
-h --help   Shows this screen 
-lr --low <low>   Passes low risk investiment 
-hr --high <high>  Passes high risk investiment' -> doc 

library(docopt) 
# retrieve the command-line arguments 
opts <- docopt(doc) 
# what are the options? Note that stripped versions of the parameters are added to the returned list 
cat(opts$high) 
cat(opts$low) 
str(opts) 

每當我試着用./test.R -lr 2000 -hr 4000它警告我說的方法包被加載並返回沒有別的運行。

  • 這是什麼錯誤?

回答

1

首先,-h被指定兩次:一次爲「幫助」,另一次爲「高」,所以你會遇到問題。爲了解決這個問題,我將使用大寫字母作爲短參數。其次,選項的參數必須爲<angular-brackets>或大寫,因此-lr不起作用。 (顯然它也需要選項和它的參數之間的空格。)我將它擴展爲與長選項相同的命名參數。

此外(雖然也許不是嚴格要求),我認爲逗號有助於澄清事情。 (編輯:顯然docopt.R不喜歡使用情況的領先./,所以我已經更新了輸出)

usage: test.R [-L <low> -H <high>] 

options: 
-h, --help     Shows this screen 
-L <low>, --low <low>  Passes low risk investiment 
-H <high>, --high <high> Passes high risk investiment 

(我發現docopt要求在http://docopt.org/我發現,他們的interactive docopt demo相當工作)

+0

謝謝您的詳細解答,但是它必須是R(R版本3.4.1)中的一個bug,來自CRAN的docopt,因爲它不起作用。 –

+1

好的,對不起,我最初將其解釋爲docopt中的一個問題(與原始版本不兼容),而不是R實現(似乎與任一版本窒息)。我發現你已經[已經提交了一個錯誤報告](https://github.com/docopt/docopt.R/issues/32),在我之前。 – r2evans

+1

我發現了錯誤。 docopt的R迭代在用法部分不處理./test.R,它必須是test.R –