这是一个简单的例子,它使用带有两个子命令的 argparse:
"""
How to have different mandatory parameters for two categories
using argparse python?
"""
import argparse
import sys
def main():
"""
Description here
"""
parser = argparse.ArgumentParser(
description='Stack Overflow 64995368 Parser'
)
parser.add_argument(
"-v",
"--verbose",
help="verbose output",
action="store_true"
)
subparser = parser.add_subparsers(
title="action",
dest='action',
required=True,
help='action sub-command help'
)
# create the subparser for the "push" command
parser_push = subparser.add_parser(
'push',
help='push help'
)
parser_push.add_argument(
'environment',
type=str,
help='push environment help'
)
parser_push.add_argument(
'instance',
type=str,
help='push instance help'
)
parser_push.add_argument(
'config',
type=str,
help='push config help'
)
# create the subparser for the "status" command
parser_status = subparser.add_parser(
'status',
help='status help'
)
parser_status.add_argument(
'environment',
type=str,
help='status environment help'
)
parser_status.add_argument(
'instance',
type=str,
help='status instance help'
)
args = parser.parse_args()
if args.action == 'push':
print('You chose push:',
args.environment, args.instance, args.config)
elif args.action == 'status':
print('You chose status:',
args.environment, args.instance)
else:
print('Something unexpected happened')
if __name__ == "__main__":
try:
sys.exit(main())
except KeyboardInterrupt:
print("\nCaught ctrl+c, exiting")
各种命令行的示例输出:
$ python3 test.py
usage: test.py [-h] [-v] {push,status} ...
test.py: error: the following arguments are required: action
$ python3 test.py -h
usage: test.py [-h] [-v] {push,status} ...
Stack Overflow 64995368 Parser
optional arguments:
-h, --help show this help message and exit
-v, --verbose verbose output
action:
{push,status} action sub-command help
push push help
status status help
$ python3 test.py push -h
usage: test.py push [-h] environment instance config
positional arguments:
environment push environment help
instance push instance help
config push config help
optional arguments:
-h, --help show this help message and exit
$ python3 test.py push
usage: test.py push [-h] environment instance config
test.py push: error: the following arguments are required: environment, instance, config
$ python3 test.py push myenv
usage: test.py push [-h] environment instance config
test.py push: error: the following arguments are required: instance, config