小编Hut*_*tch的帖子

使用 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()
Run Code Online (Sandbox Code Playgroud)

目前,当我运行python test.py arg1 arg2时,错误是

error: unrecognized arguments: arg1 arg2
Run Code Online (Sandbox Code Playgroud)

我希望代码允许用户在需要查看说明时使用 -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 …
Run Code Online (Sandbox Code Playgroud)

python argparse python-3.x

1
推荐指数
1
解决办法
3668
查看次数

标签 统计

argparse ×1

python ×1

python-3.x ×1