【问题标题】:Working with argparse need explaination of how to use it properly使用 argparse 需要解释如何正确使用它
【发布时间】:2013-11-08 22:56:55
【问题描述】:

我有 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

【问题讨论】:

标签: python django argparse


【解决方案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

我相信这应该会如您所愿。

【讨论】:

  • 我已经为您提供了问题 1 中的用例。我是 python 新手,绝对是 argparse。你能详细说明一下吗?我真正关心的是问题 1,因为它与问题 3 相关。我在任何 add_argument 方法的参数中都没有 required=True 。我收到一个错误,说 args 太少。
  • 你可以试试我刚刚发布的版本吗?我相信它应该做你想做的:)
  • FileType 的使用可能会让初学者感到困惑。
  • 最终你可能想让command_type 成为一个子解析器。如果不同的命令需要不同的参数,这将是最有用的。
  • @hpaulj:这可能有点令人困惑,但我仍然认为从一开始就使用正确的工具来完成这项工作会更好:) 我认为手册对这些事情相当清楚。跨度>
猜你喜欢
  • 2013-06-09
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
  • 2017-11-16
  • 2021-05-11
  • 2021-05-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多