GNU getopt, and command line tools that use it, allow options and arguments to be interleaved, known as permuting options (see http://www.gnu.org/software/libc/manual/html_node/Using-Getopt.html#Using-Getopt). Perl's Getopt::Long module also supports this (with qw(:config gnu_getopt)). argparse seems to not support (or even mention) permuting options.
There are many SO questions related to arg/opt order, but none seem answer this question: Can argparse be made to permute argument order like getopt?
The use case is a prototypical command line signature like GNU sort:
sort [opts] [files]
in which 1) options and files are permuted, and 2) the file list may contain zero or more arguments.
For example:
import argparse
p = argparse.ArgumentParser();
p.add_argument('files',nargs='*',default=['-']);
p.add_argument('-z',action='store_true')
p.parse_args(['-z','bar','foo']) # ok
p.parse_args(['bar','foo','-z']) # ok
p.parse_args(['bar','-z','foo']) # not okay
usage: ipython [-h] [-z] [files [files ...]]
I've tried:
I want to implement something close to the GNU sort prototype above. I am not interested in a flag that can be specified for each file (e.g., -f file1 -f file2).
Python 3.7 adds support for this with "parse_intermixed_args" - see https://docs.python.org/3.7/library/argparse.html#argparse.ArgumentParser.parse_intermixed_args