我目前正在爲我的庫編寫一個腳本,並最終陷入瞭如何設計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