我正在使用 R 包 argparse解析 R 脚本中的命令行参数。
为了便于阅读,我想在脚本的“描述”和参数的帮助中添加换行符。但是,我做不到......让我们看一个例子。给定这个脚本:
#!/usr/bin/env Rscript
require(argparse)
docstring<- "Description\nDone"
parser<- ArgumentParser(description= docstring)
args<- parser$parse_args()
当使用 -h 执行时,它应该打印:
Description
Done
但是,我收到错误:
Error in rjson::fromJSON(output) : unexpected character 'F'
Calls: <Anonymous> -> <Anonymous> -> <Anonymous>
Execution halted
像paste("Description", "Done", sep= '\n') 这样的文档字符串变体同样不成功。
编辑:传递 RawTextHelpFormatter:运气不好。
parser<- ArgumentParser(description= docstring, RawTextHelpFormatter= TRUE)
知道如何在 argparse 中添加换行符吗?
非常感谢!
达里奥
注意:在 r-help 上交叉发布:https://stat.ethz.ch/pipermail/r-help/2014-November/423722.html
sessionInfo()
R version 3.0.1 (2013-05-16)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] argparse_1.0.1 proto_0.3-10
loaded via a namespace (and not attached):
[1] findpython_1.0.1 getopt_1.20.0 rjson_0.2.13
最佳答案
经过一段时间的研究和查看代码,我找到了自己答案的解决方案:使用 formatter_class= 'argparse.RawTextHelpFormatter'
并正确转义换行符:
#!/usr/bin/env Rscript
require(argparse)
docstring<- "DESCRIPTION \\n\\
Do stuff \\n\\n\\
Do more stuff"
parser<- ArgumentParser(description= docstring, formatter_class= 'argparse.RawTextHelpFormatter')
args<- parser$parse_args()
现在它正确给出(省略启动消息):
./testParse.R -h
usage: ./testParse.R [-h]
DESCRIPTION
Do stuff
Do more stuff
optional arguments:
-h, --help show this help message and exit
@hpaulj 你的提示是正确的,我花了一段时间才弄清楚!
关于R argparse : Line breaks in description,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27150625/