Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python argparse: print epilog only when verbose

I define a parser with a description, options, and an epilog. When I run the app with --help, it outputs help with the epilog as expected. However, I only want to see the epilog if --help is accompanied with --verbose. What is the proper way to achieve this with argparse?

# example code in file test
import argparse
parser = argparse.ArgumentParser( description='description', epilog='epilog' )
parser.add_argument('-v', '--verbose', action='store_true', help='verbose help')
parser.parse_args()

When I run test as follows

$ python test -h

it yields

 usage: test [-h] [-v]

description

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  verbose help

epilog

However, what I want to see is

 usage: test [-h] [-v]

description

optional arguments:
  -h, --help     show this help message and exit
  -v, --verbose  verbose help

with the epilog shown only when I run

$ python test -h -v
like image 412
Andrey Sokolov Avatar asked Jun 23 '26 22:06

Andrey Sokolov


2 Answers

Ick. The only way I know of doing this is by writing the help output by yourself:

import argparse
parser = argparse.ArgumentParser( 
  description='description', 
  add_help=False )
parser.add_argument(
  '-h', '--help',
  action=store_true,
  dest='show_help')   
parser.add_argument(
  '-v', '--verbose', 
  action='store_true', 
  help='verbose help')
args = parser.parse_args()
if args.show_help:
  if args.verbose:
    print '%s\n%s' % (parser.format_help(), 'epilog')
  else
    parser.print_help()
  sys.exit(0)     
like image 194
2ps Avatar answered Jun 26 '26 10:06

2ps


Using the ideas suggested, here's what I came up with:

import argparse
parser = argparse.ArgumentParser( description='description', epilog='', add_help=False )
parser.add_argument('-h', '--help', action='store_true', help='show help')
parser.add_argument('-v', '--verbose', action='store_true', help='more help')
args = parser.parse_args()

if args.help:
    if args.verbose:
        parser.epilog += "epilog for %(prog)s"
    else:
        parser.epilog += "\nfor more help run '%(prog)s -h -v'"
    parser.print_help()
    parser.exit(0)

print 'the end'

The only difficulty I found with this approach is that it is no longer possible to add required options or positional arguments. A workaround for positional arguments is to use nargs='?' and do the checking manually.

like image 43
Andrey Sokolov Avatar answered Jun 26 '26 10:06

Andrey Sokolov