Customizing the help output

Here's some typical output that comes directly from the default argparse.print_help() code:

usage: ch18_ex1.py [-v] [--debug] [--dealerhit {Hit17,Stand17}]
[--resplit {ReSplit,NoReSplit,NoReSplitAces}]
[--decks DECKS] [--limit LIMIT] [--payout PAYOUT]
[-p {SomeStrategy,AnotherStrategy}]
[-b {Flat,Martingale,OneThreeTwoSix}] [-r ROUNDS]
[-s STAKE] [--samples SAMPLES] [-V] [-?]
output

Simulate Blackjack

positional arguments:
output

optional arguments:
-v, --verbose
--debug
--dealerhit {Hit17,Stand17}
--resplit {ReSplit,NoReSplit,NoReSplitAces}
--decks DECKS Decks to deal (default: 6)
--limit LIMIT
--payout PAYOUT
-p {SomeStrategy,AnotherStrategy}, --playerstrategy {SomeStrategy,AnotherStrategy}
-b {Flat,Martingale,OneThreeTwoSix}, --bet {Flat,Martingale,OneThreeTwoSix}
-r ROUNDS, --rounds ROUNDS
-s STAKE, --stake STAKE
--samples SAMPLES Samples to generate (default: 100)
-V, --version show program's version number and exit
-?, --help

The default help text is built from four things in our parser definition:

  • The usage: line is a summary of the options. We can replace the default calculation with our own usage text that omits the less commonly used details.
  • This is followed by the description. By default, the text we provide is cleaned up a bit. In this example, we provided a shabby two-word description, Simulate Blackjack, so there's no obvious cleanup.
  • Then, the arguments are shown. These come in two subgroups:
    • The positional arguments
    • The options, in the order that we defined them.
  • After this, an optional epilogue text may be shown; we didn't provide any for this definition.

In some cases, this kind of terse reminder is adequate. In other cases, however, we may need to provide more details. We have three tiers of support for more detailed help:

  • Add help= to the argument definitions: This is the place to start when customizing the help details. This will supplement the option description with more meaningful details.
  • Use one of the other help formatter classes: This is done with the formatter_class= argument when building ArgumentParser. If we want to use ArgumentDefaultsHelpFormatter, then this works with the help= values for each argument definition.
  • Extend the ArgumentParser class and override the print_usage() and print_help() methods: This allows us to write very sophisticated output. This should not be used casually. If we have options so complex that ordinary help features don't work, then perhaps we've gone too far.

Our goal is to improve usability. Even if our programs work correctly, we can build trust by providing command-line support that makes our program easier to use.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset