Search code examples
pythongetopt

How to parse two or more arguments after a option using getopt in Python?


I'm using getopt in Python now and know some basic usage. But I wonder if there is way to parse two or more arguments after a option.

e.g.

python test.py -a 111 -b 222 333

How to get both '222' and '333' when I parse option '-b'.Actually I can only catch '222'.


Solution

  • You would use argparse (why optparse, why?):

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', action='append')
    >>> parser.parse_args('--foo 1 --foo 2'.split())
    Namespace(foo=['1', '2'])
    

    From the documentation: https://docs.python.org/3/library/argparse.html

    eg:

    python test.py -a 111 -b 222 -b 333 -b 4444