Defining the order of the arguments with argparse - Python
<p>I have the following command line tool:</p>

<pre><code>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
</code></pre>

<p>The output of <code>python args.py</code> is:</p>

<pre><code>usage: args.py [-h] [--optional1 OPTIONAL1] [--optional2 OPTIONAL2]
               positional
</code></pre>

<p>however I would like to have:</p>

<pre><code>usage: args.py [-h] positional [--optional1 OPTIONAL1] [--optional2 OPTIONAL2]
</code></pre>

<p>How could I have that reordering?</p>

<p>With respect to each other the order of <code>positionals</code> is fixed - that's why they are called that.  But <code>optionals</code> (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 <code>nargs</code>.)</p>

<p>For the <code>usage</code> line, <code>argparse</code> moves the <code>positionals</code> to the end of the list, but that just a display convention.</p>

<p>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 <code>usage</code> parameter is the simplest option.  The programming way requires subclassing the help formatter and modifying a key method.</p>

python command-line command argparse args