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

Popular posts from this blog

php - failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request -

java - How to filter a backspace keyboard input -

java - Show Soft Keyboard when EditText Appears -