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>The answer is <strong>yes</strong>. A quick look at <a href="https://docs.python.org/3.6/library/argparse.html?highlight=argparse#module-argparse" rel="nofollow">the argparse documentation</a> would have answered as well.</p>

<p>Here is a very simple example, argparse is able to handle far more specific needs.</p>

<pre><code>import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--foo', '-f', help="a random options", type= str)
parser.add_argument('--bar', '-b', help="a more random option", type= int, default= 0)

print(parser.format_help())
# usage: test_args_4.py [-h] [--foo FOO] [--bar BAR]
# 
# optional arguments:
#   -h, --help         show this help message and exit
#   --foo FOO, -f FOO  a random options
#   --bar BAR, -b BAR  a more random option

args = parser.parse_args("--foo pouet".split())
print(args)  # Namespace(bar=0, foo='pouet')
print(args.foo) # pouet
print(args.bar) # 0
</code></pre>

<p>Off course, in a real script, you won't hard-code the command-line options and will call <code>parser.parse_args()</code> (without argument) instead. It will make argparse take the <code>sys.args</code> list as command-line arguments.</p>

<p>You will be able to call this script this way:</p>

<pre><code>test_args_4.py -h  # prints the help message
test_args_4.py -f pouet  # foo="pouet", bar=0 (default value)
test_args_4.py -b 42  # foo=None, bar=42
test_args_4.py -b 77 -f knock  # foo="knock", bar=77
</code></pre>

<p>You will discover a lot of other features by reading the doc ;)</p>

python python-3.x arguments