I want to emulate the behavior of most command-line utilities, where optional arguments can be put anywhere in the command line, including between positional arguments, such as in this mkdir example:
mkdir before --mode 077 after
In this case, we know that --mode takes exactly 1 argument, so before and after are both considered positional arguments. The optional part, --mode 077, can really be put anywhere in the command line.
However, with argparse, the following code does not work with this example:
# mkdir.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--mode', nargs=1)
parser.add_argument('dirs', nargs='*')
args = parser.parse_args()
Running ./mkdir.py before --mode 077 after results in:
mkdir.py: error: unrecognized arguments: after
How can I get argparse to accept an optional argument (with a fixed, known number of items) between positional ones?