Take the 2-minute tour ×

Optparse, the old version just ignores all unrecognised arguments and carries on. In most situations, this isn't ideal and was changed in argparse. But there are a few situations where you want to ignore any unrecognised arguments and parse the ones you've specified.

For example:

parser = argparse.ArgumentParser()
parser.add_argument('--foo', dest="foo")

$python myscript.py --foo 1 --bar 2
error: unrecognized arguments: --bar

Is there anyway to overwrite this?

share|improve this question

3 Answers 3

up vote 54 down vote accepted


args = parser.parse_args()


args, unknown = parser.parse_known_args()

For example,

import argparse
parser = argparse.ArgumentParser()
args, unknown = parser.parse_known_args(['--foo', 'BAR', 'spam'])
# Namespace(foo='BAR')
# ['spam']
share|improve this answer
+1 - didn't knew there was some thing like parse_known_args –  avasal Oct 10 '12 at 11:32
Nor did I! I even missed it in the docs docs.python.org/library/…. Thanks –  jdborg Oct 10 '12 at 14:11
This came up when trying to use nosetest with parseargs (it refused to allow nosetest args to be used) the reason was because I was doing parser.parse_args(None) rather than parser.parse_args([]) in my tests. –  Andy Hayden Apr 7 at 6:30

Actually argparse does still "ignore" _unrecognized_args. As long as these "unrecognized" arguments don't use the default prefix you will hear no complaints from the parser.

Using @anutbu's configuration but with the standard parse.parse_args(), if we were to execute our program with the following arguments.

$ program --foo BAR a b +cd e

We will have this Namespaced data collection to work with.

Namespace(_unrecognized_args=['a', 'b', '+cd', 'e'], foo='BAR')

If we wanted the default prefix - ignored we could change the ArgumentParser and decide we are going to use a + for our "recognized" arguments instead.

parser = argparse.ArgumentParser(prefix_chars='+')

The same command will produce

Namespace(_unrecognized_args=['--foo', 'BAR', 'a', 'b'], cd='e')

Put that in your pipe and smoke it =)


share|improve this answer

You can puts the remaining parts into a new argument with parser.add_argument('args', nargs=argparse.REMAINDER) if you want to use them.

share|improve this answer

Your Answer


