Reading named command arguments
<p>Can I use <code>argparse</code> to read named command line arguments that do not need to be in a specific order? I browsed through the <a href="https://docs.python.org/3/library/argparse.html" rel="nofollow">documentation</a> but most of it focused on displaying content based on the arguments provided (such as <code>--h</code>).</p>

<p>Right now, my script reads ordered, unnamed arguments:</p>

<blockquote>
  <p>myscript.py foo-val bar-val</p>
</blockquote>

<p>using <code>sys.argv</code>:</p>

<pre><code>foo = sys.argv[1]
bar = sys.argv[2]
</code></pre>

<p>But I would like to change the input so that it is order agnostic by naming arguments:</p>

<blockquote>
  <p>myscript.py --bar=bar-val --foo=foo-val </p>
</blockquote>

<p>You can use the <a href="https://docs.python.org/2/howto/argparse.html#introducing-optional-arguments" rel="nofollow">Optional Arguments</a> like so:</p>

<pre><code>import argparse, sys

parser=argparse.ArgumentParser()

parser.add_argument('--bar', help='Do the bar option')
parser.add_argument('--foo', help='Foo the program')

args=parser.parse_args()

print args
print sys
</code></pre>

<p>Then if you call it with <code>./prog --bar=bar-val --foo foo-val</code> it prints:</p>

<pre><code>Namespace(bar='bar-val', foo='foo-val')
['Untitled 14.py', '--bar=bar-val', '--foo', 'foo-val']
</code></pre>

<p>Or, if the user wants help argparse builds that too:</p>

<pre><code> $ ./prog -h
usage: Untitled 14.py [-h] [--bar BAR] [--foo FOO]

optional arguments:
  -h, --help  show this help message and exit
  --bar BAR   Do the bar option
  --foo FOO   Foo the program
</code></pre>

python python-3.x arguments