在Python中使用argparse处理无效参数 [英] Handle invalid arguments with argparse in Python

查看:207
本文介绍了在Python中使用argparse处理无效参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 argparse 来解析命令行参数,默认情况下收到无效的参数时,它会显示帮助消息并退出.当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.

也就是说,我相信这只会对 extra 参数有帮助,而对具有无效值的预期参数没有帮助.

That said, I believe this will only help with extra arguments, not expected arguments that have invalid values.

这篇关于在Python中使用argparse处理无效参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆