如何使用 argparse python 为两个类别设置不同的强制参数?
How to have different mandatory parameters for two categories using argparse python?
我正在编写 python 脚本,我需要根据传递的输入参数做两件事:
- 推送: 这将调用 api 到 post 一些数据。
- status: 这将调用另一个 api 来检查数据并在控制台上打印出详细信息。
当我们使用push
参数时,我们需要始终传递这三个强制参数:
- 环境
- 实例
- 配置
而当我们使用status
参数时,我们只需要传递这两个强制参数:
- 环境
- 实例
如何使用 Python 中的 argparse
以这种方式配置这些参数?我正在阅读更多关于此 here 的内容,但对如何使上述内容以良好的方式工作感到困惑?此外,使用信息应该清楚地说明使用什么输入。
这可以使用 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' )
我正在编写 python 脚本,我需要根据传递的输入参数做两件事:
- 推送: 这将调用 api 到 post 一些数据。
- status: 这将调用另一个 api 来检查数据并在控制台上打印出详细信息。
当我们使用push
参数时,我们需要始终传递这三个强制参数:
- 环境
- 实例
- 配置
而当我们使用status
参数时,我们只需要传递这两个强制参数:
- 环境
- 实例
如何使用 Python 中的 argparse
以这种方式配置这些参数?我正在阅读更多关于此 here 的内容,但对如何使上述内容以良好的方式工作感到困惑?此外,使用信息应该清楚地说明使用什么输入。
这可以使用 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' )