3

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.

2 Answers 2

6

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"] 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the response. I am guessing that I should replace '"--foo 5 --bar --baz".split()' with my actual flags that I can some how get from the ArgumentParser()?
Yes. parse_known_args doesn't require you to define any flags; anything on the command line that isn't defined is simply put (in order) in the second element of the tuple returned by parse_known_args. Flags that are recognized are parsed, removed, and used to set attributes of the first element.
Thanks again for getting back to me. Would you happen to know how to generate "--foo 5 --bar --baz".split() using ArgumentParser()? After fiddling around with it, I tried parse_args() but this returns a namespace object which can't be converted into a list object.
Both parse_args and parse_known_args just take a list of words (by default, sys.argv[1:]) as an argument. I use split as a quick-n-dirty method to generate a list from a string.
0

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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.