2016-11-26 60 views
0

我目前正在爲我的庫編寫一個腳本,並最終陷入瞭如何設計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。現在這似乎是一個小的代價,但如果我需要將所有參數都添加到腳本中,那麼這將會變得更長和更乏味。

+0

子命令呢? https://docs.python.org/3.5/library/argparse.html#sub-commands – errikos

回答

2

你可以收集所有傳遞給arc.search可選關鍵字參數到dict,然後解壓縮它,當你調用該函數:

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('-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') 
args = (parser.parse_args()) 

# Mock search 
def search(query, start_time=None, end_time=None, discover_fields=None): 
    return 'Id', ', '.join(str(x) for x in [start_time, end_time, discover_fields]) 

""" 
Checks if query is used, and starts a search 
""" 
if args.query: 
    # {name used in argparse: search parameter name} 
    query_args = { 
     'starttime': 'start_time', 
     'endtime': 'end_time', 
     'discover_fields': 'discover_fields' 
    } 
    d = vars(args) 
    real_args = {v: d[k] for k, v in query_args.items() if k in d} 
    search_id, response = search(args.query, **real_args) 

    print('The search id is {}'.format(search_id)) 
    print('Response is {}'.format(response)) 

輸出:

>python test.py -t foo -u user -p pass -q 
query -st start -et end 
The search id is Id 
Response is start, end, None 

由於一些參數名的解析器使用的名稱不同於傳遞給search的名稱需要重新映射。 vars用於從parse_args()返回的Namespace對象創建dict。然後,詞典理解遍歷映射的參數名稱,挑選給定用戶的名稱,並創建一個新的詞典,其中包含arc.search可以理解的鍵名稱。最後,**real_args在函數調用中解壓縮名爲參數的字典。

相關問題