how to access nargs of optparse-add_action?

2019-06-01 10:47发布

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.

1条回答
做自己的国王
2楼-- · 2019-06-01 11:23

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.

查看更多
登录 后发表回答