使用argparse需要解释如何正确使用它

2024-04-25 18:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三个问题。在

(一)。我希望能够使用这个python命令行程序,而不必担心参数的顺序。我在用系统argv以前和让我的用户像这样使用这个脚本: mypyscript.py create indexname http://localhost:9260 clientMap.json 这需要我的用户记住顺序。 我想要这样的东西: mypyscript.py -i indexname -c create -f clientMap.json -u http://localhost:9260 注意我是怎么把命令弄乱的。在

(二)。我将在程序中使用什么命令行变量作为条件逻辑 在我的密码里?我需要通过args.命令-类型?仪表板没问题吧?在

3)中。只有要索引的文件是可选参数。我能给add_参数传递一些可选的=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

Tags: ofto命令行程序addparser参数index
1条回答
网友
1楼 · 发布于 2024-04-25 18:50:46
  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

我相信这会像你期望的那样有效。在

相关问题 更多 >