Ruby optparse 的限制

8
我目前使用Python进行脚本编写,但出于几个原因,我希望尝试Ruby。在过去的一周里,我查看了很多示例代码并阅读了很多文档。我担心的一个问题是Ruby中缺乏适当的命令行参数解析库。Ruby专家们,请不要生气——也许我不知道。这就是我在这里的原因。
在Python中,我习惯使用argparse,在我看来它非常完美(也许是针对我的需求)。不幸的是,OptionParser不允许像argparse那样具有灵活性和功能。
我现在特别关注以下约束:
  1. How do I make mutually exclusive option lists? For e.g. a very small option list for a program called test.

    usage: test [-h] [-a | -b | -c] [-d] [filename]
    

    I can write some code like:

    # implement a ----------------------------------------------
    opts.on( "-a", "--alpha",
             "implement alpha") do
        #...
    end
    

    and so on. But then, I've no way to make a, b and c mutually exclusive unless I code a permutation of those and do some error handling. For e.g.

    test -ab #should through an error
    

    In Python, I could do this in a very easy way:

    # create an command line argument parser object
    cmd_line_parser = argparse.ArgumentParser()
    
    # create a mutually exclusive group
    cmd_line_group = cmd_line_parser.add_mutually_exclusive_group()
    
    1. Secondly, I've no way of pairing -d with -a unless I specifically write code for this permutation. This is insane.

    2. I've to write the [OPTION] list myself; I've no way to know if I am wrong or right unless and until I do a blackbox testing for all possible input permutations and map them to the blackbox list.

    3. Moreover, compulsory arguments again need to be handled using special code.

有没有使用 Ruby 中的 optparse 或其他库来处理这些约束条件的简单方法?
1个回答

11

有一个docopt库,它同时支持Python和Ruby。 test程序的规范如下:

usage: test [-h] [-a | -b | -c] [-d] [<filename>]

a、b、c选项是互斥的(-ab会产生错误),它支持组合选项:-ad-da等。

要使filename参数成为必需的:

usage: test [-h] [-a | -b | -c] [-d] <filename>

哇,那太疯狂了。史诗级别的。没话说。我到底干了什么这么久。真是太棒了。非常感谢。 - p0lAris

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接