【问题标题】:Allow unknown arguments using argparse使用 argparse 允许未知参数
【发布时间】: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


【解决方案1】:
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))

【讨论】:

  • 那行得通,我还添加了帮助开关以添加有关参数所需内容的 cmets。
【解决方案2】:

试试下面的代码:-

 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.add_argument('arg1')
 parser.add_argument('arg2')

 args, unknown = parser.parse_known_args()

您所有未知的参数都将在 unknown 中进行解析,而所有未知参数都将在 args 中进行解析。

【讨论】:

  • 我意识到这个答案可能不是 OP 想要的,但正是我在 Google 搜索中寻找的东西让我来到了这里。
【解决方案3】:

您需要将这些参数添加到解析器:

parser.add_argument("--arg1", "-a1", dest='arg1', type=str)
parser.add_argument("--arg2","-a2", dest='arg2', type=str)

如果这些参数没有参数required=true,您将能够在没有此参数的情况下调用程序,因此您可以只使用 -h 标志。使用参数运行程序:

python test.py --arg1 "Argument" --arg2 "Argument"

然后,要在变量中包含参数,您必须阅读它们:

args = parser.parse_args()
argument1=args.arg1
argument2=args.arg2

【讨论】:

  • 这根本不是真的。 ArgumentParser 支持解析未知参数,如上面 mujjiga 的回答中所回答的那样。
猜你喜欢
  • 2020-11-29
  • 2013-03-28
  • 2018-07-04
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 2022-12-31
  • 2021-09-11
  • 2021-03-06
相关资源
最近更新 更多