Is there any way to get argparse.ArgumentParser.parse_args() not to exit on argument errors?

孤者浪人 提交于 2020-01-23 11:16:49

问题


For example:

import argparse

parser = arparse.ArgumentParser()
# parser.add_argument(...) ...
args = parser.parse_args(args_list)

The problem is, parser.parse_args automatically exits if there is an error in args_list. Is there a setting that gets it to raise a friendlier exception instead? I do not want to have to catch a SystemExit and extract the needed error message from it if there is any way around it.


回答1:


You could use

args, unknown = parser.parse_known_args(args_list)

Then, any unknown arguments will be simply returned in unknown.

For example,

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--bar', action='store_true')
parser.add_argument('cheese')
args, unknown = parser.parse_known_args(['--swallow', 'gouda', 'african'])
print(args)
# Namespace(bar=False, cheese='gouda')

print(unknown)
# ['--swallow', 'african']


来源:https://stackoverflow.com/questions/16004901/is-there-any-way-to-get-argparse-argumentparser-parse-args-not-to-exit-on-argu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!