我想更改由于输入错误的参数值或输入没有任何值的参数而导致的错误的默认消息。
我有代码test.py:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-n',
'--number',
type=int,
help='Specify a number to print',
required=False)
args = parser.parse_args()
if __name__ == "__main__":
if not args.number:
print("Hello")
else:
print(args.number)
当我输入 python test.py 时,我有输出 Hello
当我输入 python test.py --number 1 我有输出 1
但是当我输入 python test.py --number 我得到了:
test.py:错误:参数-n/--number:需要一个参数
但我想在该输出中包含自定义消息,例如“请写入要打印的数字” - 如何从argparser“捕获”错误并自定义它的消息
另外,当我得到 invalid int value 时,我希望得到相同的错误消息
如示例所示:
python test.py --number k
test.py:错误:参数-n/--number:无效的int值:'k'
我想要:
python test.py --number k
请写下要打印的号码
python test.py --number
请写下要打印的号码
要做你想做的事,你可以重写ArgumentParser类的error方法,你可以在https://github.com/python/cpython/blob/3.10/Lib/argparse.py查看argparse源代码
#instead of doing this
parser = argparser.ArgumentParser()
#do this
class CustomArgumentParser(argparse.ArgumentParser)
def error(self, message):
raise Exception('Your message')
#then use the new class
parser = CustomArgumentParser(exit_on_error=False)
与 Carlos Correa 的答案类似,您可以直接使用 MethodType 设置解析器对象的错误方法。
import argparse, types
parser = argparser.ArgumentParser()
def custom_error(self, message):
raise Exception('Your message')
# Set the object's error method directly
parser.error = types.MethodType(custom_error, parser)
这可以避免专门为此目的创建新类的一些笨拙。