python - 使用 argparse 允许未知参数
问题描述
我有一个 python 脚本,需要用户输入两个参数来运行它,参数可以命名为任何东西。
我还使用 argparse 允许用户使用开关“-h”来获取运行脚本所需的说明。
问题是,现在我使用了 argparse,当我通过脚本传递两个随机命名的参数时出现错误。
import argparse
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help',
help='To run this script please provide two arguments')
parser.parse_args()
目前,当我运行python test.py arg1 arg2时,错误是
error: unrecognized arguments: arg1 arg2
如果需要查看说明,我希望代码允许用户使用 -h 运行 test.py,但也允许他们使用任意两个参数运行脚本。
带有帮助标签的分辨率,为用户提供有关所需参数的上下文。
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument('-h', '--help', action='help', help='To run this script please provide two arguments: first argument should be your scorm package name, second argument should be your html file name. Note: Any current zipped folder in the run directory with the same scorm package name will be overwritten.')
parser.add_argument('package_name', action="store", help='Please provide your scorm package name as the first argument')
parser.add_argument('html_file_name', action="store", help='Please provide your html file name as the second argument')
parser.parse_args()
解决方案
import argparse
parser = argparse.ArgumentParser(description='sample')
# Add mandatory arguments
parser.add_argument('arg1', action="store")
parser.add_argument('arg2', action="store")
# Parse the arguments
args = parser.parse_args()
# sample usage of args
print (float(args.arg1) + float(args.arg2))
推荐阅读
- c# - 我想从我的服务器中选择两个日期之间的数据。C#
- swift - Swift MacOS抓取焦点窗口的窗口ID
- android - 是否可以减少leanback android tv应用程序中headerFragment的宽度
- php - 加入后的学说 ORM 序列化
- javascript - 数字转 UTF-8 字符
- c# - 使用 Microsoft Graph API 发送带有附件的回复
- c - Python调用C语言时返回值异常
- java - 在 JUnit5 中测试失败后如何运行代码?
- javascript - D3 - 堆积图表在条形顶部显示总值
- javascript - 如何在 ORDER BY 和限制之后动态添加查询参数