如果您想同时允许--feature
和--no-feature
(以最后一个为准)
这使用户可以使用--feature
创建shell别名,并使用--no-feature
覆盖它。
Python 3.9及以上版本
parser.add_argument('--feature', default=True, action=argparse.BooleanOptionalAction)
Python 3.8 及以下版本
我建议使用mgilson的答案:
parser.add_argument('--feature', dest='feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
如果您不想同时允许--feature
和--no-feature
您可以使用互斥组:
feature_parser = parser.add_mutually_exclusive_group(required=False)
feature_parser.add_argument('--feature', dest='feature', action='store_true')
feature_parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)
如果你需要设置多个,你可以使用这个辅助程序:
def add_bool_arg(parser, name, default=False):
group = parser.add_mutually_exclusive_group(required=False)
group.add_argument('--' + name, dest=name, action='store_true')
group.add_argument('--no-' + name, dest=name, action='store_false')
parser.set_defaults(**{name:default})
add_bool_arg(parser, 'useful-feature')
add_bool_arg(parser, 'even-more-useful-feature')
parser.add_argument('--feature', dest='feature', default=False, action='store_true')
。这个解决方案将确保您始终获得一个值为True
或False
的bool
类型。(这个解决方案有一个限制:您的选项必须具有默认值。) - Trevor Boyd Smithdistutils.util.strtobool(x)
来源于另一个stackoverflow问题) - Trevor Boyd Smithparser.add_argument('--my_bool', action='store_true', default=False)
。 - AruniRCimport distutils.util
而不是import disutils
进行导入。请参见此答案。 - Osama Darargparse
的开发人员充分意识到一些用户试图将像“True”或“False”这样的字符串处理为布尔值,但已经拒绝重新定义基本的Pythonbool
函数的提议。解析可以表示True/False
的单词太具有语言特定性,最好由程序员自己处理(而不是硬编码)。简单地说,type
参数是一个function
。 - hpaulj