问题
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