简体   繁体   English

如果 ArgumentParser 遇到未知参数,则引发异常

[英]Raise exception if ArgumentParser encounters unknown argument

I'm using the Python (version 3.9.4) library argparse to parse a small number of option flags.我正在使用 Python(版本 3.9.4)库argparse来解析少量选项标志。 For a number of reasons, I'd like to handle errors in my code rather than argparse.ArgumentParser .出于多种原因,我想处理代码中的错误而不是argparse.ArgumentParser Namely, how an unrecognized argument is handled.即,如何处理无法识别的参数。 For example, if I ran my-python-program --foobar , I'd like to be able to catch an exception and perform work there.例如,如果我运行my-python-program --foobar ,我希望能够捕获异常并在那里执行工作。 This testcase disables almost all of the errors I've tried, except for an invalid argument:这个测试用例禁用了我尝试过的几乎所有错误,除了一个无效的参数:

import argparse
import sys

try:
  parser = argparse.ArgumentParser(add_help=False, exit_on_error=False, usage=None)
  parser.add_argument("--help", action="store_true", default=False)
  parser.add_argument("--hello", default="Hello, world!")
  args = parser.parse_args()
  print(args.help, args.hello)

except Exception as err:
  print("a problem occurred!", file=sys.stderr)
  print(f"error: {err}", file=sys.stderr)

Instead, running my-python-program --foobar gives me:相反,运行my-python-program --foobar会给我:

usage: my-python-program [--help] [--hello HELLO]
my-python-program: error: unrecognized arguments: --foobar

If you look at the Python argparse source code , you can see that it calls self.error on an error.如果您查看 Python argparse 源代码,您可以看到它在出错时调用self.error This function (at the bottom of the file), by default, prints the error message and quits.默认情况下,此 function(位于文件底部)会打印错误消息并退出。 You can override this method in a subclass to raise an error instead.您可以在子类中重写此方法以引发错误。

import argparse
import sys

class MyArgumentParser(argparse.ArgumentParser):
  """An argument parser that raises an error, instead of quits"""
  def error(self, message):
    raise ValueError(message)

try:
  parser = MyArgumentParser(add_help=False, exit_on_error=False, usage=None)
  parser.add_argument("--help", action="store_true", default=False)
  parser.add_argument("--hello", default="Hello, world!")
  args = parser.parse_args()
  print(args.help, args.hello)

except Exception as err:
  print("a problem occurred!", file=sys.stderr)
  print(f"error: {err}", file=sys.stderr)

Output: Output:

$ python3 test.py --foobar
a problem occurred!
error: unrecognized arguments: --foobar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM