使用 argparse 允许未知参数 [英] Allow unknown arguments using argparse

查看:26
本文介绍了使用 argparse 允许未知参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 脚本,需要用户输入两个参数来运行它,参数可以命名为任何名称.

I have a python script that requires the user to enter two arguments to run it, the arguments could be named anything.

我还使用了 argparse 来允许用户使用开关-h"来获取运行脚本所需内容的说明.

I have also used argparse to allow the users to use a switch '-h' to get instructions of what is required to run the script.

问题是,现在我使用了 argparse,当我通过脚本传递两个随机命名的参数时出现错误.

The problem is that now I have used argparse I am getting an error when I pass my two randomly named arguments with the script.

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 错误是

currently when I run python test.py arg1 arg2 the error is

error: unrecognized arguments: arg1 arg2

如果需要查看说明,我希望代码允许用户使用 -h 运行 test.py,但也允许他们使用任意两个参数运行脚本.

I would like the code to allow the user to run test.py with a -h if required to see the instructions but also allow them to run the script with any two arguments as well.

解决方案,带有帮助标签,可为用户提供有关所需参数的上下文.

Resolution with help tag to provide the user with context regarding the arguments required.

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

这篇关于使用 argparse 允许未知参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆