栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在argparse中显示所有子解析器的帮助?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在argparse中显示所有子解析器的帮助?

问题在于:

subparsers=parser.add_subparsers(dest='action')subparsers.add_parser('Restart',parents=[general_group,second_group])subparsers.add_parser('Start',parents=[general_group])

您是

general_group
作为子解析器的父级添加的,因此主解析器不了解它们,导致
./script.py-h
不显示
--threads
。如果计划将其作为所有子解析器的父级,则应将其作为顶级解析器的父级:

parser = argparse.ArgumentParser(parents=[general_group])subparsers=parser.add_subparsers(dest='action')subparsers.add_parser('Restart',parents=[second_group])subparsers.add_parser('Start')

结果是:

$ python script.py -husage: script.py [-h] [--threads] {Restart,Start} ...positional arguments:  {Restart,Start}optional arguments:  -h, --help       show this help message and exit  --threads

但是请注意,在这种情况下,该选项仅是父解析器的一部分,而不是子解析器的一部分,这意味着:

$python script.py --threads Start

是正确的,而:

$ python script.py Start --threadsusage: script.py [-h] [--threads] {Restart,Start} ...script.py: error: unrecognized arguments: --threads

因为

--threads
不是由子解析器“继承”。如果要
--threads
在子解析器中也包含它,则必须在其
parents
参数中指定它:

parser = argparse.ArgumentParser(parents=[general_group])subparsers=parser.add_subparsers(dest='action')subparsers.add_parser('Restart',parents=[general_group, second_group])subparsers.add_parser('Start', parents=[general_group])

这应该做您想要的:

$ python script.py -husage: script.py [-h] [--threads] {Restart,Start} ...positional arguments:  {Restart,Start}optional arguments:  -h, --help       show this help message and exit  --threads$ python script.py Start -husage: script.py Start [-h] [--threads]optional arguments:  -h, --help  show this help message and exit  --threads


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/517200.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号