gdbb
gdbb

Reputation: 41

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'.

Upvotes: 0

Views: 127

Answers (2)

gdbb
gdbb

Reputation: 41

Parameter 'nargs' can do that in argparse.

>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', nargs=2)
>>> parser.add_argument('bar', nargs=1)
>>> parser.parse_args('c --foo a b'.split())
Namespace(bar=['c'], foo=['a', 'b'])

e.g.

python --foo 111 222

argparse documentation

Upvotes: 0

Kelvin
Kelvin

Reputation: 1367

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

Upvotes: 1

Related Questions