Search code examples
pythonargparse

argparse to accept random arguments


I have a Python application that implements argparse with a set of arguments declared:

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--arg1",
        default="dev",
        choices=["real", "test", "dev"],
        help="arg 1"
    )
    parser.add_argument("--arg2", default="0", help="arg 2")
    parser.add_argument(
        "--arg3",
        nargs="+",
        default=["one", "two"],
        choices=["one", "two"],
        help="arg 3",
    )
    parser.add_argument("--arg4", action="store_true", help="arg 4")
    parser.add_argument("--arg5", action="store_true", help="arg 5")
    parser.add_argument("--arg6", action="store_true", help="arg 6")
    parser.add_argument("--arg7", default=None, help="arg 7")

    args = parser.parse_args()

If I send an argument that is not defined in these declarations, I get this exception:

error: unrecognized arguments: arg8 value

Is it possible to indicate argparse to accept non declared arguments?


Solution

  • ArgumentParser.parse_known_args parses what it can, and returns a tuple consisting of the Namespace object with the results and a list of unrecognized arguments.