python - How to use top-level arguments with subparsers in argparse -
in python's argparse, how implement top-level arguments while still using commands implemented subparsers?
i'm trying implement --version
argument show program's version number, argparse giving me error: few arguments
because i'm not specifying sub-command 1 of subparsers.
my code:
import argparse parser = argparse.argumentparser() parser.add_argument( '-v', '--version', help='show version.', action='store_true', default=false ) subparsers = parser.add_subparsers( dest="command", ) list_parser = subparsers.add_parser('list') parser.parse_args(['--version'])
the output:
usage: myscript.py [-h] [-v] {list} ... myscript.py: error: few arguments
if need version work, can this:
import argparse parser = argparse.argumentparser() parser.add_argument( '-v', '--version', action='version', version='%(prog)s 1.0', )
subparsers won't bother more; special version
action processed , exits script before parser looks subcommands.
Comments
Post a Comment