how to access nargs of optparse-add_action?

末鹿安然 提交于 2019-12-08 04:34:17

问题


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:


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.



来源:https://stackoverflow.com/questions/24285311/how-to-access-nargs-of-optparse-add-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!