Search code examples
pythonoptparse

How to apply optparse to parse a group of parameters


In python we use optparse to format our CLI parameters. However, I don't know how to apply add_option() on supporting combined or a groups of arguments.

For example:

1) How can my CLI support combined paramters:

eg:

python test.py -ah

actually, this command can expand to:

python test.py -a -h

2) How can my CLI support groups parameters:

eg:

python test.py -f f1.txt f2.txt f3.txt

in this example: space is the separator, we can also define comma also as the separator.

I don't know whether optparse can support.


Solution

  • You should not be using optparse for new projects. According to the docs:

    Deprecated since version 2.7: The optparse module is deprecated and will not be developed further; development will continue with the argparse module.

    The functionality you are looking for is built into argparse:

    import argparse
    
    parser = argparse.ArgumentParser('Test program')
    parser.add_argument('-a', action='store_true')
    parser.add_argument('-v', action='store_true')
    parser.add_argument('-f', nargs='+')
    args = parser.parse_args()
    
    print(args)
    

    This yields:

    $ python parser.py -av -f f1.txt f2.txt f3.txt
    Namespace(a=True, f=['f1.txt', 'f2.txt', 'f3.txt'], v=True)