首页 > 解决方案 > 使用 argparse 的参数名称

问题描述

# import the necessary packages
import argparse
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-n", "--name", required=True,
    help="name of the user")
args = vars(ap.parse_args())
# display a friendly message to the user
print("Hi there {}, it's nice to meet you!".format(args["name"]))

如果我使用 运行此代码-h,我会得到:

$ python simple_example.py --help
usage: simple_example.py [-h] -n NAME
optional arguments:
  -h, --help            show this help message and exit
  -n NAME, --name NAME  name of the user

是什么NAME意思,在-nand之后--name?代码中没有指定在任何地方使用字符串“NAME”,它是怎么出现在这里的?如果它是“名称”而不是“名称”,那将是有意义的。

标签: pythonargparse

解决方案


NAME表示您需要传递的实际参数。这是一种区分需要类似参数的标志-n(例如 --n Kyathari有效,-n本身无效)和不接受类似参数的标志的方法-h


推荐阅读