[英]Working with argparse need explaination of how to use it properly
我有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)。 仅文件到索引是可选参数。 我可以将一些可选的= True参数传递给add_argument吗? 我该如何处理?
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
这里有什么问题? 我个人认为这取决于用例,对于您的旧系统,有话要说。 特别是与子解析器一起使用时。
破折号是默认且通常理解的方式
有一个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
我相信这应该可以按照您的预期工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.