2013-12-10 36 views
1

在我的搜索文本文件(日誌)的腳本中,我使用argparse來獲取命令行參數並定義搜索條件。Python argparse 1 vs 2參數的互斥組

我使用--df和 - dt來定義從= =到期間。我還想要一個可選的--period,它將通過使用由自定義操作(例如「week」)解析的某些定義的字符串來覆蓋--df和 - dt。現在,我希望--period與--df AND --dt互斥,但據我所知,add_mutually_exclusive_group()是不可能的。

我曾嘗試下面的代碼,但沒有成功:

parser = argparse.ArgumentParser(description='Search the file') 

dfgroup = parser.add_mutually_exclusive_group() 
dfgroup.add_argument(
    '--df', 
    type=dateparser.parse, 
    metavar='DATETIME', 
    help='date and/or time to search from' 
) 
dfgroup.add_argument(
    '--period', 
    action='store', #should be a custom action 
    metavar='PERIOD', 
    help='the period to search within (mutually exclusive with --df and --dt)' 
) 
dtgroup = parser.add_mutually_exclusive_group() 
dtgroup.add_argument(
    '--dt', 
    type=dateparser.parse, 
    metavar='DATETIME', 
    help='date and/or time to search to' 
) 
dtgroup.add_argument(
    '--period', 
    action='store', #should be a custom action 
    metavar='PERIOD', 
    help='the period to search within (mutually exclusive with --df and --dt)' 
) 

有沒有什麼辦法可以讓--period既--df和--dt參數互斥(和周圍的其他方法) ?

回答

2

如果您對此解決方案絕對肯定並且很滿意,那麼我有一個解決方法。在add_argument使用nargs這樣

import argparse 
parser = argparse.ArgumentParser(description="Hello") 
group = parser.add_mutually_exclusive_group() 
group.add_argument('--period', action='store') 
group.add_argument('--df_dt', nargs='+') 
args = parser.parse_args() 

執行你的腳本

program.py --period <period> 
program.py --df_dt <df> <dt> 

然後,當提供這種使用

df = args.df_dt[0] 
dt = args.df_dt[1] 

希望幫助

+1

實際訪問的參數,這是一個非常比我的更好的主意。我會用這個。 – agnsaft