Search code examples
pythonpython-2.7optparse

how to access nargs of optparse-add_action?


I am working on one requirement for my project using command line utility:optparse.

Suppose if I am using add_option utility like below:

parser.add_option('-c','--categories', dest='Categories', nargs=4 )

I wanted to add check for -c option if user does not input 4 arguments.

something like this:

if options.Categories is None:
   for loop_iterate on nargs:
        options.Categories[loop_iterate] = raw_input('Enter Input')

How to access nargs of add_option().?

PS:I do not want to have check using print.help() and do exit(-1)

Please somebody help.


Solution

  • AFAIK optparse doesn't provide that value in the public API via the result of parse_args, but you don't need it. You can simply name the constant before using it:

    NUM_CATEGORIES = 4
    
    # ...
    
    parser.add_option('-c', '--categories', dest='categories', nargs=NUM_CATEGORIES)
    
    # later
    
    if not options.categories:
        options.categories = [raw_input('Enter input: ') for _ in range(NUM_CATEGORIES)]
    

    In fact the add_option method returns the Option object which does have the nargs field, so you could do:

    categories_opt = parser.add_option(..., nargs=4)
    
    # ...
    
    if not options.categories:
        options.categories = [raw_input('Enter input: ') for _ in range(categories_opt.nargs)]
    

    However I really don't see how this is better than using a costant in the first place.