gpt4 book ai didi

python - 抑制 argparse 错误消息 - Python

转载 作者:行者123 更新时间:2023-12-05 00:41:18 25 4
gpt4 key购买 nike

我正在使用 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)

所以我只希望打印 "Invalid arguments or number of arguments" 而没有别的。但是,然后我执行代码例如:

./foo --BOGUS

我收到了完整的使用信息:

usage: foo [-h]
foo: error: too few arguments
foo: Invalid arguments or number of arguments

我怎样才能做到这一点?

最佳答案

您可以使用 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)

另一种选择是继承 ArgumentParser 并覆盖 exit方法。

关于python - 抑制 argparse 错误消息 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35830919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com