pythonparsingcommand-line-argumentsargparsesubcommand

Default sub-command, or handling no sub-command with argparse


How can I have a default sub-command, or handle the case where no sub-command is given using argparse?

import argparse

a = argparse.ArgumentParser()
b = a.add_subparsers()
b.add_parser('hi')
a.parse_args()

Here I'd like a command to be selected, or the arguments to be handled based only on the next highest level of parser (in this case the top-level parser).

joiner@X:~/src> python3 default_subcommand.py
usage: default_subcommand.py [-h] {hi} ...
default_subcommand.py: error: too few arguments

Solution

  • It seems I've stumbled on the solution eventually myself.

    If the command is optional, then this makes the command an option. In my original parser configuration, I had a package command that could take a range of possible steps, or it would perform all steps if none was given. This makes the step a choice:

    parser = argparse.ArgumentParser()
    
    command_parser = subparsers.add_parser('command')
    command_parser.add_argument('--step', choices=['prepare', 'configure', 'compile', 'stage', 'package'])
    
    ...other command parsers
    
    parsed_args = parser.parse_args()
    
    if parsed_args.step is None:
        do all the steps...