Search code examples
pythonargparse

Control formatting of the argparse help argument list?


import argparse
parser = argparse.ArgumentParser(prog='tool')
args = [('-u', '--upf', 'ref. upf', dict(required='True')),
        ('-s', '--skew', 'ref. skew', {}),
        ('-m', '--model', 'ref. model', {})]
for args1, args2, desc, options in args:  
     parser.add_argument(args1, args2, help=desc, **options)

parser.print_help()

Output:

usage: capcheck [-h] -u UPF [-s SKEW] [-m MODEL]

optional arguments:
  -h, --help            show this help message and exit
  -u UPF, --upf UPF     ref. upf
  -s SKEW, --skew SKEW  ref. skew
  -m MODEL, --model MODEL
                        ref. model

How do I print ref. model in the same line as -m MODEL, --model MODEL instead of that appearing on a separate line when I run the script with -h option?


Solution

  • You could supply formatter_class argument:

    parser = argparse.ArgumentParser(prog='tool',
      formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=27))
    
    args = [('-u', '--upf', 'ref. upf', dict(required='True')),
            ('-s', '--skew', 'ref. skew', {}),
            ('-m', '--model', 'ref. model', {})]
    for args1, args2, desc, options in args:  
         parser.add_argument(args1, args2, help=desc, **options)
    
    parser.print_help()
    

    Note: Implementation of argparse.HelpFormatter is private only the name is public. Therefore the code might stop working in future versions of argparse. File a feature request to provide a public interface for the customization of max_help_position on http://bugs.python.org/

    Output

    usage: tool [-h] -u UPF [-s SKEW] [-m MODEL]
    
    optional arguments:
      -h, --help               show this help message and exit
      -u UPF, --upf UPF        ref. upf
      -s SKEW, --skew SKEW     ref. skew
      -m MODEL, --model MODEL  ref. model