首页 > 解决方案 > 使用 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()

标签: pythonpython-3.xargparse

解决方案


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))

推荐阅读