如何访问optparse-add_action的nargs? [英] how to access nargs of optparse-add_action?

查看:90
本文介绍了如何访问optparse-add_action的nargs?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用命令行实用程序optparse处理项目的一项要求.

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

假设我使用如下所示的add_option实用程序:

Suppose if I am using add_option utility like below:

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

如果用户未输入4个参数,我想为-c选项添加check.

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

类似这样的东西:

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

如何访问add_option()的nargs ??

How to access nargs of add_option().?

PS:我不想使用print.help()进行检查并执行exit(-1)

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

请有人帮忙.

推荐答案

AFAIK optparse不会通过parse_args的结果在公共API中提供该值,但是您不需要它. 您可以在使用常量之前简单地命名它:

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)]

实际上,add_option方法返回的Option对象确实具有 nargs 字段,因此您可以这样做:

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.

这篇关于如何访问optparse-add_action的nargs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆