2013-10-29 33 views
0

我有3個問題。使用argparse需要說明如何正確使用它

1)。我希望能夠使用這個python命令行程序,而不用擔心參數的順序。我以前使用sys.argv,並讓我的用戶使用如下腳本: mypyscript.py create indexname http://localhost:9260 clientMap.json 這就要求我的用戶記住訂單。 我想要的是這樣的: mypyscript.py -i indexname -c create -f clientMap.json -u http://localhost:9260 請注意我是如何毀壞訂單的。 2)。我的代碼中將使用什麼命令行變量作爲條件邏輯 ?我需要通過args.command-type訪問它嗎?短跑是好的? 3)。只有文件到索引是可選參數。我可以傳遞給add_argument一些可選的= True參數或其他東西嗎?我該如何處理?

import argparse 

parser = argparse.ArgumentParser() 
parser.add_argument("-c","--command-type", help="The command to run against ElasticSearch are one of these: create|delete|status") 
parser.add_argument("-i","--index_name", help="Name of ElasticSearch index to run the command against") 
parser.add_argument("-u", "--elastic-search-url", help="Base URl of ElasticSearch") 
parser.add_argument("-f", "--file_to_index", default = 'false', help="The file name of the index map") 

args = parser.parse_args() 


print args.elastic_search_url 
+0

只需使用[docopt](http://docopt.org/) –

回答

1
  1. 問題是什麼嗎?我個人認爲這取決於用例,對於您的舊系統有些事要說。特別是在與子分析器一起使用時。

  2. 破折號是默認的通常理解的方式

  3. 有一個required=True參數,它告訴​​需要什麼。

對於command-type我會建議使用choices參數,所以它會被自動限制爲create,delete,status

而且,你可以考慮增加一個正則表達式來驗證URL的情況下,你可以添加這使用type參數。

這裏是我的版本的你的論點代碼:

import argparse 

parser = argparse.ArgumentParser() 
parser.add_argument(
    '-c', 
    '--command-type', 
    required=True, 
    help='The command to run against ElasticSearch', 
    choices=('create', 'delete', 'status'), 
) 
parser.add_argument(
    '-i', 
    '--index_name', 
    required=True, 
    help='Name of ElasticSearch index to run the command against', 
) 
parser.add_argument(
    '-u', 
    '--elastic-search-url', 
    required=True, 
    help='Base URl of ElasticSearch', 
) 
parser.add_argument(
    '-f', 
    '--file_to_index', 
    type=argparse.FileType(), 
    help='The file name of the index map', 
) 


args = parser.parse_args() 

print args 

我相信,你期望它應該工作。

+0

我在第1個問題中爲您提供了用例。我是python的新手,絕對是argparse。你能否詳細說明一下?我真正關心的是問題1,因爲它與問題3有關。在任何add_argument方法的參數中,我都沒有required = True。我得到一個錯誤,說太少的參數。 –

+0

你可以試試我剛發佈的版本嗎?我相信它應該做你想要的東西:) – Wolph

+0

'FileType'的使用可能會讓初學者感到困惑。 – hpaulj