3

I have the following command line tool:

import argparse

parser = argparse.ArgumentParser(description = "A cool application.")
parser.add_argument('positional')
parser.add_argument('--optional1')
parser.add_argument('--optional2')

args = parser.parse_args()
print args.positionals

The output of python args.py is:

usage: args.py [-h] [--optional1 OPTIONAL1] [--optional2 OPTIONAL2]
               positional

however I would like to have:

usage: args.py [-h] positional [--optional1 OPTIONAL1] [--optional2 OPTIONAL2]

How could I have that reordering?

cybertextron
  • 10,547
  • 28
  • 104
  • 208
  • Could you still run it with your desired output ? Reading the API it says the order doesn't really matter with optional and positional arguments. https://docs.python.org/3/howto/argparse.html#combining-positional-and-optional-arguments – MooingRawr Oct 14 '16 at 20:17

2 Answers2

2

You would either have to provide your own help formatter, or specify an explicit usage string:

parser = argparse.ArgumentParser(
    description="A cool application.",
    usage="args.py [-h] positional [--optional1 OPTIONAL1] [--optional2 OPTIONAL2]")

The order in the help message, though, does not affect the order in which you can specify the arguments. argparse processes any defined options left-to-right, then assigns any remaining arguments to the positional parameters from left to right. Options and positional arguments can, for the most part, be mixed.

chepner
  • 497,756
  • 71
  • 530
  • 681
2

With respect to each other the order of positionals is fixed - that's why they are called that. But optionals (the flagged arguments) can occur in any order, and usually can be interspersed with the postionals (there are some practical constrains when allowing variable length nargs.)

For the usage line, argparse moves the positionals to the end of the list, but that just a display convention.

There have been SO questions about changing that display order, but I think that is usually not needed. If you must change the display order, using a custom usage parameter is the simplest option. The programming way requires subclassing the help formatter and modifying a key method.

hpaulj
  • 221,503
  • 14
  • 230
  • 353