如何访问optparseadd\u操作的nargs?

2024-04-19 05:49:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用命令行为我的项目处理一个需求实用程序:optparse。你知道吗

假设我使用如下的add\u option实用程序:

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

如果用户没有输入4个参数,我想为-c选项添加check。你知道吗

像这样的:

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

如何访问add\u option()的nargs。?你知道吗

我不想用print.help()和do exit(-1)进行检查

请有人来帮忙。你知道吗


Tags: 项目用户命令实用程序loopaddparserdest
1条回答
网友
1楼 · 发布于 2024-04-19 05:49:00

AFAIKoptparse不会通过parse_args的结果在公共API中提供该值,但您不需要它。 您只需在使用常量之前命名它:

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对象,该对象具有^{}字段,因此可以执行以下操作:

categories_opt = parser.add_option(..., nargs=4)

# ...

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

然而,我真的不明白这是如何比使用成本在第一位好。你知道吗

相关问题 更多 >