[英]How to have different mandatory parameters for two categories using argparse python?
我正在处理 python 脚本,我需要根据传递的输入参数做两件事:
当我们使用push
参数时,我们需要始终传递这三个强制性参数:
当我们使用status
参数时,我们只需要传递这两个强制性参数:
如何使用 Python 中的argparse
以这种方式配置这些参数? 我在这里阅读了更多关于此的内容,但对如何使上述事情以良好的方式工作感到困惑? 此外,使用消息应该清楚地说明使用什么输入。
这可以使用argparse
吗? 任何例子将不胜感激。 一般我们将呼吁的方法push
,将使用这些参数,同样的情况下status
,我们将调用将使用这些参数的其他方法。
你可以做这样的事情,使用set_defaults
为每个子命令属性一个处理程序。
import argparse
def push(args):
return (args.environment, args.instance, args.config)
def status(args):
return (args.environment, args.instance)
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers()
# create the parser for the push command
push_parser = subparsers.add_parser('push')
push_parser.set_defaults(func=push)
push_parser.add_argument('--environment', type=str)
push_parser.add_argument('--instance', type=str)
push_parser.add_argument('--config', type=str)
# create the parser for the status command
status_parser = subparsers.add_parser('status')
status_parser.set_defaults(func=status)
status_parser.add_argument('--environment', type=str)
status_parser.add_argument('--instance', type=str)
args = parser.parse_args(['push', '--environment=a', '--instance=b', '--config=c'])
print(args.func(args))
这是一个使用 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
直接使用 sys.argv 内容通常更容易。 https://www.tutorialspoint.com/python/python_command_line_arguments.htm
#! /usr/bin/env python3
import sys
s_args = sys .argv ## s_args[0] = script_name.py
def push( environment, instance, config ):
print( 'PUSH command:', environment, instance, config )
def status( environment, instance ):
print( 'STATUS command:', environment, instance )
##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if __name__ == '__main__':
if len( s_args ) < 4:
print( 'missing args:' )
print( ' PUSH environment instance config' )
print( ' STATUS environment instance' )
elif s_args[1] .lower() == 'push':
if len( s_args ) < 5:
print( 'missing args for PUSH command:' )
print( ' PUSH environment instance config' )
else:
push( s_args[2], s_args[3], s_args[4] )
elif s_args[1] .lower() == 'status':
if len( s_args ) < 4:
print( 'missing args for STATUS command:' )
print( ' STATUS environment instance' )
else:
status( s_args[2], s_args[3] )
else:
print( 'incorrect command:' )
print( ' PUSH environment instance config' )
print( ' STATUS environment instance' )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.