Search code examples
pythondocstring

Print docstring with default --help function


I have a code that looks like:

#!/usr/bin/env python
'''Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage
'''
import argparse
import sys

import matplotlib.pyplot as plt
import numpy as np

parser = argparse.ArgumentParser()
#  parser.add_argument('--dos', help='Plot the dos', required=True)
parser.add_argument('--dos', nargs='*', help='Files to plot')
parser.add_argument('--label', nargs='*', help='Label of the files')
parser.add_argument('--fermi', help='Fermi Energy')
args = parser.parse_args()

If I run this code with python foo.py -h, I get the output:

usage: foo.py [-h] [--dos [DOS ...]] [--label [LABEL ...]] [--fermi FERMI]

options:
  -h, --help           show this help message and exit
  --dos [DOS ...]      Files to plot
  --label [LABEL ...]  Label of the files
  --fermi FERMI        Fermi Energy

I know I can separately print the docstring using print(__doc__).

But, I want the python foo.py -h to print both the docstring together with the present -h output. That is, python foo.py -h should give:

Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage

usage: foo.py [-h] [--dos [DOS ...]] [--label [LABEL ...]] [--fermi FERMI]
    
    options:
      -h, --help           show this help message and exit
      --dos [DOS ...]      Files to plot
      --label [LABEL ...]  Label of the files
      --fermi FERMI        Fermi Energy

Is this possible?


Solution

  • You can get the local module docstring with __doc__ If you use that as the description to ArgumentParser() such as:

    parser = argparse.ArgumentParser(description=__doc__)
    

    It will come pretty close to what you want:

    usage: foo.py [-h] [--dos [DOS ...]] [--label [LABEL ...]] [--fermi FERMI]
    
    Plot multiple DOS/PDOS in a single plot run python dplot.py -h for more usage
    
    optional arguments:
      -h, --help           show this help message and exit
      --dos [DOS ...]      Files to plot
      --label [LABEL ...]  Label of the files
      --fermi FERMI        Fermi Energy