Andy
Andy

Reputation: 950

argparse allowing arbitrary flags

Is there a way to allow argparse to accept arbitrary flags?

For example, I have a wrapper over git push called gitter

I would prefer to not have to specify all the flags available to git push as there are many.

However, I still want to be able to do something like

gitter --all --no-verify

Is there a way for argparse to take arbitrary flags and have those flags be passed onto git push?

If I do gitter --fake-flag, I immediately get an error without the chance of parsing out the flags.

Upvotes: 3

Views: 643

Answers (2)

aronbo
aronbo

Reputation: 333

Why not use a bash script for gitter instead of Python? Something like:

#!/bin/bash
git push --alwaysArg "$@"

When run:

gitter --all --no-verify

The resulting command will be:

git push --alwaysArg --all --no-verify

Upvotes: 0

chepner
chepner

Reputation: 532518

You can use parse_known_args to leave unrecognized flags in a list.

p = ArgumentParser()
p.add_argument("--foo")
args, remaining = p.parse_known_args("--foo 5 --bar --baz".split())

# args.foo == 5
# remaining = ["--bar", "--baz"]

Upvotes: 6

Related Questions