抑制 argparse 错误消息 - Python

cyb*_*ron 1 python command-line arguments

我正在使用 argparse 来解析命令行参数。然而此时,我有一个不寻常的请求:我想抑制错误信息。例如:

 # !/usr/bin/env python
 try:
        parser = argparse.ArgumentParser(description='Parse')
        parser.add_argument('url', metavar='URL', type=str, nargs='+', 
                            help='Specify URL')
 except:
        print("Invalid arguments or number of arguments")
        exit(2)
Run Code Online (Sandbox Code Playgroud)

所以我只希望打印出来"Invalid arguments or number of arguments",别无其他。但是,然后我执行代码,例如:

./foo --BOGUS
Run Code Online (Sandbox Code Playgroud)

我收到完整的使用信息:

usage: foo [-h]
foo: error: too few arguments
foo: Invalid arguments or number of arguments 
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

Eug*_*ash 5

您可以contextlib.redirect_stderr用来抑制以下输出argparse

import io
from contextlib import redirect_stderr

try:
    f = io.StringIO()
    with redirect_stderr(f):
        parser.parse_args()
except:
    print("Invalid arguments or number of arguments")
    exit(2)
Run Code Online (Sandbox Code Playgroud)

另一种选择是子类化ArgumentParser并覆盖该exit方法。