Python argparse allow combined flags
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon
--
Chapters
00:00 Python Argparse Allow Combined Flags
00:26 Answer 1 Score 2
00:49 Accepted Answer Score 6
01:15 Thank you
--
Full question
https://stackoverflow.com/questions/2128...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #commandlinearguments #argparse
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Romantic Lands Beckon
--
Chapters
00:00 Python Argparse Allow Combined Flags
00:26 Answer 1 Score 2
00:49 Accepted Answer Score 6
01:15 Thank you
--
Full question
https://stackoverflow.com/questions/2128...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #commandlinearguments #argparse
#avk47
ACCEPTED ANSWER
Score 6
You can achieve this with store_const:
parser = argparse.ArgumentParser()
parser.add_argument('-a', action='store_const', const=True, default=False)
parser.add_argument('-b', action='store_const', const=True, default=False)
args = parser.parse_args()
Then you can call this from the command line either with -a -b or with -ab (or -a, or -b).
Edit: and if you want one of the flags to take an argument, you need to pass it as the last item of the chain. So if a takes an argument, you'd need to do -bcda something
ANSWER 2
Score 2
Here's what I found with a little Googling:
Several short options can be joined together, using only a single - prefix, as long as only the last option (or none of them) requires a value:
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', action='store_true')
>>> parser.add_argument('-y', action='store_true')
>>> parser.add_argument('-z')
>>> parser.parse_args('-xyzZ'.split())
Namespace(x=True, y=True, z='Z')
http://docs.python.org/dev/library/argparse.html#option-value-syntax