pythonargparseoptparse

Python argparse ignore unrecognised arguments


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")
parser.parse_args()

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

Is there anyway to override this?


Solution

  • Replace

    args = parser.parse_args()
    

    with

    args, unknown = parser.parse_known_args()
    

    For example,

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--foo')
    args, unknown = parser.parse_known_args(['--foo', 'BAR', 'spam'])
    print(args)
    # Namespace(foo='BAR')
    print(unknown)
    # ['spam']