argparse epilog call function?

Peter Otten __peter__ at web.de
Tue Jun 27 11:35:27 EDT 2017


Didymus wrote:

> Greetings,
> 
> I might be barking up the wrong tree, but was wondering if there's a way
> to have the argpasre epilog call a function. for example:
> 
> epilog=Examples()
> 
> Where Examples is:
> 
> def Examples():
>     text = """Lots of examples"""
>     print(text.format())
> 
> I've place this in and found that it prints out no matter if I use the -h
> or not and also it prints first.... If I do:
> 
> epilog='Single Example'
> 
> it works as intended, unfortunately, I need to show several examples. Just
> wondering if someone has found a why to do this (without making a custom
> help).

Here's a way using a custom *formatter*:

$ cat epilog.py
import argparse

class MyHelpFormatter(argparse.HelpFormatter):
    def add_text(self, text):
        if callable(text):
            text = text()
        return super().add_text(text)

def examples():
    return "yadda yadda"

parser = argparse.ArgumentParser(
    epilog=examples,
    formatter_class=MyHelpFormatter
)
parser.add_argument("--foo")

parser.parse_args()
$ python3 epilog.py -h
usage: epilog.py [-h] [--foo FOO]

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

yadda yadda
$ 





More information about the Python-list mailing list