【发布时间】:2019-12-16 02:44:11
【问题描述】:
我有一个 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,但也允许他们使用任意两个参数运行脚本。
Resolution 带有帮助标签,为用户提供有关所需参数的上下文。
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()
【问题讨论】:
-
你读过argparse tutorial吗?您似乎没有声明任何参数,但如果您想知道如何使用和记录它们,您需要的知识比快速回答要多得多。
-
也可以考虑 click 作为替代方案,它很受欢迎,因为它更易于使用。
-
你需要
add_argument右边parameters(nargs/required/...)
标签: python python-3.x argparse