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

后端 未结 6 2175
终归单人心
终归单人心 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:11

    This took me a little while to figure out, but you can use the callback action to your options to get this done. Checkout how I grab an arbitrary number of args to the "--file" flag in this example.

    from optparse import OptionParser,
    
    def cb(option, opt_str, value, parser):
            args=[]
            for arg in parser.rargs:
                    if arg[0] != "-":
                            args.append(arg)
                    else:
                            del parser.rargs[:len(args)]
                            break
            if getattr(parser.values, option.dest):
                    args.extend(getattr(parser.values, option.dest))
            setattr(parser.values, option.dest, args)
    
    parser=OptionParser()
    parser.add_option("-q", "--quiet",
            action="store_false", dest="verbose",
            help="be vewwy quiet (I'm hunting wabbits)")
    parser.add_option("-f", "--filename",
            action="callback", callback=cb, dest="file")
    
    (options, args) = parser.parse_args()
    
    print options.file
    print args
    

    Only side effect is that you get your args in a list instead of tuple. But that could be easily fixed, for my particular use case a list is desirable.

提交回复
热议问题