我目前正在为我的库编写一个脚本,并最终陷入了如何设计argparse,这将会有很多选项和子参数。使用许多可选的子参数设计argparse
目前我设计的搜索功能,它具有以下选项,一些必需的,有些不是:
- search_session_id - 要求
- user_session_id - 要求
- discover_fields - 可选
- START_TIME - 可选
- end_time - 可选
- summary_fields - 可选
- field_summary - 可选
- local_search - 可选
我的问题是那么下面:
我怎样才能让argparse和if语句,如果所有自选需要一起工作,而且还如果只定义其中的一个,那么工作?
如果我需要检查每一个组合,我最终会是这样的:
#!/usr/bin/env python3
"""Script to generate searches on the ArcSight Logger"""
import arcsightrest
import argparse
parser = argparse.ArgumentParser(description='Script used to send search '
'queries to ArcSight Logger API')
parser.add_argument('-t', '--target',
help='IP Address of the Loggger', required=True)
parser.add_argument('-u', '--username',
help='Username to access the logger', required=True)
parser.add_argument('-p', '--password',
help='Password to access the logger', required=True)
parser.add_argument('-ussl', '--unsecuressl', action='store_true',
help='Disable ssl warnings',)
parser.add_argument('-w', '--wait', action='store_true',
help='Wait for query to finish',)
parser.add_argument('-q', '--query',
help='Query to be used in the search')
parser.add_argument('-st', '--starttime',
help='From which time the query should look')
parser.add_argument('-et', '--endtime',
help='To which time the query should look')
parser.add_argument('-e', '--event',
help='Events based input search id')
parser.add_argument('-s', '--status',
help='Status of running search')
args = (parser.parse_args())
"""
Sets the target Logger Server
"""
arcsightrest.ArcsightLogger.TARGET = args.target
"""
Gets login token from the Logger API
"""
arc = arcsightrest.ArcsightLogger(args.username, args.password,
args.unsecuressl)
"""
Checks if query is used, and starts a search
"""
if args.query:
if args.starttime:
search_id, response = arc.search(args.query, start_time=args.starttime,
end_time=args.endtime)
search_id, response = arc.search(args.query)
if args.starttime and args.discover_fields:
search_id, response = arc.search(args.query, start_time=args.starttime,
end_time=args.endtime,
discover_fields=args.discover_fields)
print('The search id is {}'.format(search_id))
if response:
print('The search has successfully started')
正如你所看到的,我可没有结束持续,使如果有每一个组合语句的可选参数。必须有一个更简单的方法来设计这个?如果我只是将它解析为kwargs,它们将不会以正确的格式发送,或者我会要求使用脚本的人编写诸如end_time=SOMETIME
而不是仅仅--endtime TIME
。现在这似乎是一个小的代价,但如果我需要将所有参数都添加到脚本中,那么这将会变得更长和更乏味。
子命令呢? https://docs.python.org/3.5/library/argparse.html#sub-commands – errikos