Python3 Argparse元变量括号奇怪地解析 [英] Python3 Argparse metavar brackets parsed weirdly

查看:21
本文介绍了Python3 Argparse元变量括号奇怪地解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python3 中使用 argparse,我得到了一些奇怪的东西:

I am using argparse in python3, and I get some strange things:

我使用的代码的简短版本是:

A short version of code that I'm using is:

argparser = argparse.ArgumentParser(description='add/remove items')
argparser.add_argument('-a', action='append',     metavar="Item(s)", help='add one or more items to the list')
argparser.add_argument('-r', action='append',     metavar="Item(s)", help='remove one or more items from the list')
args = argparser.parse_args()

当我使用 -h 标志运行脚本时,我得到以下输出:

When I run the script with the -h flag, I get this output:

usage: test.py [-h] [-a Items)] [-r Item(s]

add/remove items

optional arguments:
  -h, --help  show this help message and exit
  -a CPE(s)   add one or more items to the list
  -r CPE(s)   remove one or more items from the list

请注意第一行中括号的奇怪解析.

Mind the weird parsing of the brackets in the first line.

这是什么原因造成的,我该如何解决?

What causes this, and how do I solve this?

推荐答案

因为您希望拥有多个项目的可能性.使用 argparse 执行此操作的另一种方法如下:

Since you want to have the possibility of having multiple items. Another way to do this with argparse is as follows:

import argparse
argparser = argparse.ArgumentParser(description='add/remove items')
argparser.add_argument('-a', metavar="item", nargs="*", help='add one or more items to the list')
argparser.add_argument('-r', metavar="item", nargs="*", help='remove one or more items from the list')
args = argparser.parse_args()

关键点是 nargs="*"(0 个或多个参数)的使用.帮助变为:

The key point is the use of nargs="*" (0 or more arguments). The help becomes:

usage: test.py [-h] [-a [item [item ...]]] [-r [item [item ...]]]

这样,您就不必使用Item(s)",而且您也遵循标准做法.

This way, you do not have to use "Item(s)", and you also follow a standard practice.

PS:我明白你想做什么.使用 action="append",您实际上允许用户指定多个 -a-r 选项.在这种情况下,您绝对应该编写 "Item"(而不是Item(s)"),因为每个选项都需要一个项目.这也解决了您的问题(您的帮助消息应表明可以提供多个 -a-r 选项).

PS: I see what you wanted to do. With action="append", you are actually allowing the user to specify multiple -a and -r options. In this case, you should definitely write "Item" (and not "Item(s)"), since each option takes a single item. This solves your problem too (your help message should indicate that multiple -a and -r options can be given).

这篇关于Python3 Argparse元变量括号奇怪地解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆