How to take set multiple variables using argparse, both required and optional variables?
<p>How do you deal with multiple inputs via <code>argparse</code>, especially when there are default inputs and optional inputs?</p>

<p>Within my script <code>file.py</code>, users must input two parameters, which I have in a list</p>

<pre><code>parameters_list = [parameter1, parameter2, parameter3]

parameter1 = ""  # normally in the script, I would set these
parameter2 = ""
parameter3 = ""
</code></pre>

<p>The third parameter <code>parameter3</code> is a default parameter.</p>

<p>Now, to my mind, users could include the flags at run time <code>python file.py --parameters = 'parameter1', 'parameter2'</code></p>

<pre><code>parser = argparse.ArgumentParser()
parser.add_argument('parameters', nargs = '*', help = 'input program parameters')
params = parser.parse_args()
</code></pre>

<p>However</p>

<ol>
<li><p>This doesn't parse how users have input the parameters, like:</p>

<p><code>--parameters = 'parameter1', 'parameter2'</code></p></li>
<li><p>How do you deal with the default parameter <code>parameter3</code>?</p>

<p>At the moment, this will throw at error, as the variable <code>parameter3</code> has been defined in the script, but isn't defined by <code>argparse</code>.</p></li>
</ol>

<p>I would just define separate parameters for each:</p>

<pre><code>p = ArgumentParser()
p.add_argument("arg1")
p.add_argument("arg2")
p.add_argument("arg3", default=5, nargs='?')
</code></pre>

<p>and require calls like</p>

<pre><code>$ python file.py 3 2
$ python file.py 3 2 6
</code></pre>

python argparse optional