user2756376
user2756376

Reputation: 117

argparse with "+" option

I have been using argparse to parse command line options and worked great. Now I would like to use + instead of - for some options.

Ex: script.py +opt -f <filename>

Is it possible to use such + options with argparse?

Upvotes: 0

Views: 246

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121584

You can set the prefix_chars option to something other than '-':

parser = argparse.ArgumentParser(prefix_chars='-+')

at which point you can start using either - or + in the definition of arguments:

>>> import argparse
>>> parser = argparse.ArgumentParser(prefix_chars='-+')
>>> parser.add_argument('+opt', action='store_true')
_StoreTrueAction(option_strings=['+opt'], dest='opt', nargs=0, const=True, default=False, type=None, choices=None, help=None, metavar=None)
>>> parser.add_argument('-f')
_StoreAction(option_strings=['-f'], dest='f', nargs=None, const=None, default=None, type=None, choices=None, help=None, metavar=None)
>>> parser.parse_args(['+opt', '-f', '<filename>'])
Namespace(f='<filename>', opt=True)

The above defines +opt; you have to use the right prefix to invoke it, -opt won't work.

Upvotes: 4

Related Questions