Python argparse : how to detect duplicated optional argument?

感情迁移 提交于 2019-12-04 03:43:57

问题


I'm using argparse with optional parameter, but I want to avoid having something like this : script.py -a 1 -b -a 2 Here we have twice the optional parameter 'a', and only the second parameter is returned. I want either to get both values or get an error message. How should I define the argument ?

[Edit] This is the code:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-a', dest='alpha', action='store', nargs='?')
parser.add_argument('-b', dest='beta', action='store', nargs='?')

params, undefParams = self.parser.parse_known_args()

回答1:


append action will collect the values from repeated use in a list

parser.add_argument('-a', '--alpha', action='append')

producing an args namespace like:

namespace(alpha=['1','3'], b='4')

After parsing you can check args.alpha, and accept or complain about the number of values. parser.error('repeated -a') can be used to issue an argparse style error message.

You could implement similar functionality in a custom Action class, but that requires understanding the basic structure and operation of such a class. I can't think anything that can be done in an Action that can't just as well be done in the appended list after.

https://stackoverflow.com/a/23032953/901925 is an answer with a no-repeats custom Action.

Why are you using nargs='?' with flagged arguments like this? Without a const parameter this is nearly useless (see the nargs=? section in the docs).

Another similar SO: Python argparse with nargs behaviour incorrect



来源:https://stackoverflow.com/questions/30149851/python-argparse-how-to-detect-duplicated-optional-argument

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