I believe you want Python 3.7's parse_intermixed_args: https://docs.python.org/3/library/argparse.html#argparse.ArgumentParser.parse_intermixed_args

A quick test seems to work:


import argparse

p = argparse.ArgumentParser()
p.add_argument('files', nargs='*')
p.add_argument('-f', '--force', action='store_true')

print(p.parse_intermixed_args())


$ python3 rm.py x -f y
Namespace(files=['x', 'y'], force=True)




On Wed, Oct 9, 2019, 9:50 PM brent bejot <brent.bejot@gmail.com> wrote:
Hello all,

Aspiring contributor here.  I am not at all certain that this is the right place to discuss this.  Do refer me to a better location if I'm out of place.

I would like to add a simple feature to the argparse library.  I frequently find myself writing small utilities, stylistically similar to unix's "rm" whose main parameter(s) get bundled into a list and it doesn't matter if flags are sprinkled throughout.

e.g.  "rm foo.txt -f bar.txt" removes both foo.txt and bar.txt forcefully.

Doing this in argparse currently is cumbersome at best (though I would be happy to be proved wrong on that), so I rarely implement it as a feature.

Of note, calling parser.add_argument with nargs="..." or nargs="A..." or nargs="*" gets close, but will not allow you to intermix other flags between your list.

I have a working modification of argparse.py that I could commit, but I know there's several steps between here and there - I just don't know what those steps are.

Any direction would be very much appreciated.

Thanks!
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/MPWEGVUQADXMTR27GPLX2GT2Z27LRZQU/
Code of Conduct: http://python.org/psf/codeofconduct/