OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Using the same option multiple times in Python's argparse

  • Thread starter Thread starter John Allard
  • Start date Start date
J

John Allard

Guest
I'm trying to write a script that accepts multiple input sources and does something to each one. Something like this

Code:
./my_script.py \
    -i input1_url input1_name input1_other_var \
    -i input2_url input2_name input2_other_var \
    -i input3_url input3_name
# notice inputX_other_var is optional

But I can't quite figure out how to do this using argparse. It seems that it's set up so that each option flag can only be used once. I know how to associate multiple arguments with a single option (nargs='*' or nargs='+'), but that still won't let me use the -i flag multiple times. How do I go about accomplishing this?

Just to be clear, what I would like in the end is a list of lists of strings. So

Code:
[["input1_url", "input1_name", "input1_other"],
 ["input2_url", "input2_name", "input2_other"],
 ["input3_url", "input3_name"]]
<p>I'm trying to write a script that accepts multiple input sources and does something to each one. Something like this</p>

<pre><code>./my_script.py \
-i input1_url input1_name input1_other_var \
-i input2_url input2_name input2_other_var \
-i input3_url input3_name
# notice inputX_other_var is optional
</code></pre>

<p>But I can't quite figure out how to do this using <code>argparse</code>. It seems that it's set up so that each option flag can only be used once. I know how to associate multiple arguments with a single option (<code>nargs='*'</code> or <code>nargs='+'</code>), but that still won't let me use the <code>-i</code> flag multiple times. How do I go about accomplishing this?</p>

<p>Just to be clear, what I would like in the end is a list of lists of strings. So</p>

<pre><code>[["input1_url", "input1_name", "input1_other"],
["input2_url", "input2_name", "input2_other"],
["input3_url", "input3_name"]]
</code></pre>
 
Top