Search code examples
pythonargparse

Specify many option in argparse using *


I have a question for you! I have developed a command line tools with many options using argparse. Here is a simplified version of what I have:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--skip-part1', action='store_true', default=False)
parser.add_argument('--skip-part2', action='store_true', default=False)
parser.add_argument('--skip-part3', action='store_true', default=False)
parser.add_argument('--skip-part4', action='store_true', default=False)

I would like the user to be able to select all optional skip arguments by typing something like

myscript.py --skip-*

Even more advanced, using regular expression:

myscript.py --skip-part[1-3]

to select the first three options only.

Do you know how I could obtain such behavior?

Thanks


Solution

  • You could try something like this:

    parser.add_argument('--skip', action='store', default=None, nargs=1) # nargs = 1 means that 1 argument is accepted
    

    When you call something like myscript.py --skip 1-3 args.skip == ["1-3"] will be true. So you get a list with one string. With this string you can do whatever you want. You could split it at "-" to get the start and the end for Example.