在 Python 中使用 argparse 处理无效参数 [英] Handle invalid arguments with argparse in Python
问题描述
我正在使用 argparse
来解析命令行参数,默认情况下,在接收到无效参数时,它会打印帮助消息并退出.当 argparse 收到无效参数时,是否可以自定义它的行为?
I am using argparse
to parse command line arguments and by default on receiving invalid arguments it prints help message and exit. Is it possible to customize the behavior of argparse when it receives invalid arguments?
通常我想捕捉所有无效的参数并用它们做一些事情.我正在寻找类似的东西:
Generally I want to catch all invalid arguments and do stuff with them. I am looking for something like:
parser = argparse.ArgumentParser()
# add some arguments here
try:
parser.parse_args()
except InvalidArgvsError, iae:
print "handle this invalid argument '{arg}' my way!".format(arg=iae.get_arg())
这样我就可以:
>> python example.py --invalid some_text
handle this invalid argument 'invalid' my way!
推荐答案
您可能想要使用 parse_known_args
然后查看元组中的第二项,看看哪些参数没有被理解.
You might want to use parse_known_args
and then take a look at the second item in the tuple to see what arguments were not understood.
也就是说,我相信这只会有助于额外参数,而不是具有无效值的预期参数.
That said, I believe this will only help with extra arguments, not expected arguments that have invalid values.
这篇关于在 Python 中使用 argparse 处理无效参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!