问题在于:
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


