Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python argparse print usage text after description

Is there a way to print usage text after the description text with python argparse? I have my cmd line argparse working, but i would like to print version info before usage info.

Edit:

version: 1.0

usage: blahcmd [-h] [-help] 

some lovely help
like image 403
ldgorman Avatar asked Mar 13 '14 14:03

ldgorman


Video Answer


2 Answers

The argparse module does not provide any option to add a "prolog". When the help is displayed it always start with usage:. The best you can do is to customize the usage text adding the version number, using the usage parameter when you instantiate the ArgumentParser:

import argparse

parser = argparse.ArgumentParser(usage='Any text you want\n')

Note that the help will still start with usage:.

A dirty workaround that might work is to start the usage message with a \r:

>>> import argparse
>>> usage = '\r{}\nusage: %(prog)s etc.'.format('Version a b'.ljust(len('usage:')))
>>> parser = argparse.ArgumentParser(usage=usage)
>>> parser.parse_args(['-h'])
Version a b
usage:  etc.

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

I don't think that this usage of \r is portable. There are probably some terminals where this trick doesn't work. I've ljusted the version string to make sure that when the trick works, the whole usage: string disappears from string and you don't get things like v1.2e: when using short version strings.

Note: you must manually create the whole usage text now.

like image 102
Bakuriu Avatar answered Oct 26 '22 20:10

Bakuriu


Here's an ugly hack (see my comment on the original question):

Define your own subclass of HelpFormatter to pass to the parser with the formatter_class option. The subclass should probably override the _format_usage method. This isn't entirely recommended, since the interface for defining your own formatting class was never made public.

from argparse import ArgumentParser, HelpFormatter
from gettext import gettext as _

class VersionedHelp(HelpFormatter):
    def _format_usage(self, usage, actions, groups, prefix=None):
        if prefix is None:
            prefix = _('Version: x.y\n\nusage: ')
        return HelpFormatter._format_usage(self, usage, actions, groups, prefix)

p = ArgumentParser(formatter_class=VersionedHelp)
p.parse_args()
like image 27
chepner Avatar answered Oct 26 '22 20:10

chepner