3

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.

Matt
  • 21,026
  • 18
  • 63
  • 115
  • possible duplicate of [Python: After raising argparse.ArgumentError, argparse raises generic error](http://stackoverflow.com/questions/15691762/python-after-raising-argparse-argumenterror-argparse-raises-generic-error) – Martijn Pieters Apr 14 '13 at 22:07
  • The answer there solves your problem here. – Martijn Pieters Apr 14 '13 at 22:07
  • 1
    possible duplicate of [Python argparse and controlling/overriding the exit status code](http://stackoverflow.com/questions/5943249/python-argparse-and-controlling-overriding-the-exit-status-code) – jscs Apr 14 '13 at 22:21

1 Answers1

7

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']
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677