【问题标题】:R argparse: Line breaks in descriptionR argparse:描述中的换行符
【发布时间】:2014-12-09 17:51:09
【问题描述】:

我正在使用 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    

【问题讨论】:

  • Python argparse 有几个 Raw 帮助格式化程序类来保留换行符。默认格式化程序会进行自己的换行。那些其他格式化程序是否移植到R
  • 感谢您回复 hpaulj。我尝试了您的建议,但没有成功(请参阅问题的编辑)。

标签: r argparse


【解决方案1】:

玩了一会并查看代码后,我找到了自己答案的解决方案:使用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 你的提示是正确的,我花了一段时间才弄明白!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多