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>One method is to parse out the parameters as comma separated values.</p>

<pre><code>import argparse
import sys
parser = argparse.ArgumentParser()
parser.add_argument('--parameters',nargs='*',help="input program parameters")
args,unknown = parser.parse_known_args()
if(unknown):
   print("Do not use spaces!")
   sys.exit()
parameters = args.parameters
parameters = parameters[0].split(',')
parameter1 = parameters[0]
parameter2 = parameters[1]
parameter3 = "your_value" if len(parameters) &lt; 3 else params[2]
</code></pre>

<p>Of course the user would have to input the params as (no spaces):</p>

<pre><code>--parameters='parameter1','parameter2','parameter3'
</code></pre>

<p>Also note that to use <code>--parameters</code> the argument you add to the parser must match.</p>

python argparse optional