With Python's optparse module, how do you create an option that takes a variable number of arguments?

后端 未结 6 2148
终归单人心
终归单人心 2021-02-13 19:38

With Perl\'s Getopt::Long you can easily define command-line options that take a variable number of arguments:

foo.pl --files a.txt             --ve         


        
6条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 20:31

    I recently has this issue myself: I was on Python 2.6 and needed an option to take a variable number of arguments. I tried to use Dave's solution but found that it wouldn't work without also explicitly setting nargs to 0.

    def arg_list(option, opt_str, value, parser):
        args = set()
        for arg in parser.rargs:
            if arg[0] == '-':
                break
            args.add(arg)
            parser.rargs.pop(0)
        setattr(parser.values, option.dest, args)
    
    parser=OptionParser()
    parser.disable_interspersed_args()
    parser.add_option("-f", "--filename", action="callback", callback=arg_list,
                      dest="file", nargs=0)
    
    (options, args) = parser.parse_args()
    

    The problem was that, by default, a new option added by add_options is assumed to have nargs = 1 and when nargs > 0 OptionParser will pop items off rargs and assign them to value before any callbacks are called. Thus, for options that do not specify nargs, rargs will always be off by one by the time your callback is called.

    This callback is can be used for any number of options, just have callback_args be the function to be called instead of setattr.

提交回复
热议问题