0

我有 3 个问题。

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 一些 optional = 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
4

1 回答 1

1
  1. 这里的问题是什么?我个人认为这取决于用例,对于您的旧系统有话要说。尤其是与子解析器一起使用时。

  2. 破折号是默认且普遍理解的方式

  3. 有一个required=True论据告诉argparse我们需要什么。

对于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

我相信这应该像你期望的那样工作。

于 2013-10-29T16:42:00.663 回答