I'm using argparse in python3. In my script, I have some subparsers, a positional argument and some optional arguments. I have an optional argument to pass in any number of file paths, and it's using nargs='*'
. The usage message for my script displays like this:
usage: myprog.py subparser1 [-h] [--dir DIR]
[--files [FILES [FILES ...]]]
positional_arg
But if you actually put the positional_arg
after the --files
flag as suggested by this usage message, I think the parser ends up consuming it as a file path instead (because of the nargs='*'
), and then throws an error since it doesn't find the required positional_arg
.
I think the way the usage message is printed is misleading. Since I have multiple subparsers, I would like to find a way to change all the usage messages (without typing them all by hand using the usage=
argument) just so that the positional argument is displayed first, hopefully clearing up the confusion.
So my main question is how do I change the way the arguments are ordered inside the usage portion of the argparse message?
EDIT to address one possible solution that doesn't work for me.
I don't want to add the --files
flag as a positional argument with nargs='*'
. Firstly, because that makes it now shows up in the "positional arguments" section of the help message instead of in the "optional arguments" section with the rest of my optional arguments so it makes it look like it is required, even though you could pass it 0 arguments.
Secondly, because because if I wanted to have another flag that takes any number of arguments in addition to the --files
(e.g. --folders
), and if I made them both positional arguments, I'd run into the same problem where the first one would keep consuming arguments until the end. If I made one positional and one optional then the misleading usage message is still a problem.