Python argparse : how to detect duplicated optional argument?

守給你的承諾、 提交于 2019-12-01 20:42:33
hpaulj

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

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