Using Python's argparse
module, is there a way to order sub-commands created through the use of subparsers in the help output?
Asked
Active
Viewed 452 times
1

jd.
- 10,678
- 3
- 46
- 55
-
looks like duplicate of : http://stackoverflow.com/questions/12268602/sort-argparse-help-alphabetically – Jakub Czaplicki Mar 19 '13 at 12:54
-
The question you linked to is about the order of arguments. I need to sort the sub-commands. – jd. Mar 19 '13 at 13:20
1 Answers
2
I actually found a way using argparse.HelpFormatter
.
class CustomHelpFormatter(argparse.HelpFormatter):
def _iter_indented_subactions(self, action):
try:
get_subactions = action._get_subactions
except AttributeError:
pass
else:
self._indent()
if isinstance(action, argparse._SubParsersAction):
for subaction in sorted(get_subactions(), key=lambda x: x.dest):
yield subaction
else:
for subaction in get_subactions():
yield subaction
self._dedent()

jd.
- 10,678
- 3
- 46
- 55