How can I print a Python file's docstring when executing it?

PythonDocstring

Python Problem Overview


I have a Python script with a docstring. When the parsing of the command-line arguments does not succeed, I want to print the docstring for the user's information.

Is there any way to do this?

Minimal example

#!/usr/bin/env python
"""
Usage: script.py

This describes the script.
"""

import sys


if len(sys.argv) < 2:
    print("<here comes the docstring>")

Python Solutions


Solution 1 - Python

The docstring is stored in the module's __doc__ global.

print(__doc__)

By the way, this goes for any module: import sys; print(sys.__doc__). Docstrings of functions and classes are also in their __doc__ attribute.

Solution 2 - Python

Argument parsing should always be done with argparse.

You can display the __doc__ string by passing it to the description parameter of Argparse:

#!/usr/bin/env python
"""
This describes the script.
"""


if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser(description=__doc__)
    # Add your arguments here
    parser.add_argument("-f", "--file", dest="myFilenameVariable",
                        required=True,
                        help="write report to FILE", metavar="FILE")
    args = parser.parse_args()
    print(args.myFilenameVariable)

If you call this mysuperscript.py and execute it you get:

$ ./mysuperscript.py --help
usage: mysuperscript.py [-h] -f FILE

This describes the script.

optional arguments:
  -h, --help            show this help message and exit
  -f FILE, --file FILE  write report to FILE

Solution 3 - Python

Here is an alternative that does not hardcode the script's filename, but instead uses sys.argv[0] to print it. Using %(scriptName)s instead of %s improves readability of the code.

#!/usr/bin/env python
"""
Usage: %(scriptName)s

This describes the script.
"""

import sys
if len(sys.argv) < 2:
   print __doc__ % {'scriptName' : sys.argv[0].split("/")[-1]}
   sys.exit(0)

Solution 4 - Python

This will print the __doc__ string when --help is the only argument.

if __name__=='__main__':
 if len(sys.argv)==2 and sys.argv[1]=='--help':
    print(__doc__)

Works for both:

  • ./yourscriptname.py --help
  • python3 yourscriptname.py --help

Solution 5 - Python

An enhancement of @MartinThoma's answer so it prints multi-line docstrings inspired by https://stackoverflow.com/questions/3853722/python-argparse-how-to-insert-newline-in-the-help-text...

> Argument parsing should always be done with argparse. > > You can display the doc string by passing it to the description > parameter of Argparse: > > > #!/usr/bin/env python > """ > This summarizes the script. > > Additional descriptive paragraph(s). > """ # Edited this docstring > > > if __name__ == '__main__': > from argparse import ArgumentParser, RawTextHelpFormatter # Edited this line > parser = ArgumentParser(description=__doc__ > formatter_class=RawTextHelpFormatter) # Added this line > # Add your arguments here > parser.add_argument("-f", "--file", dest="myFilenameVariable", > required=True, > help="write report to FILE", metavar="FILE") > args = parser.parse_args() > print(args.myFilenameVariable) > > If you call this mysuperscript.py and execute it you get: > > > $ ./mysuperscript.py --help > usage: mysuperscript.py [-h] -f FILE > > This summarizes the script. > > Additional descriptive paragraph(s). > > optional arguments: > -h, --help show this help message and exit > -f FILE, --file FILE write report to FILE >

Without the addition of the formatter_class the output would not have the line break in the docstring.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthiasView Question on Stackoverflow
Solution 1 - PythonPetr ViktorinView Answer on Stackoverflow
Solution 2 - PythonMartin ThomaView Answer on Stackoverflow
Solution 3 - Pythonwint3rschlaeferView Answer on Stackoverflow
Solution 4 - PythonMr CaTView Answer on Stackoverflow
Solution 5 - Pythonjhale1805View Answer on Stackoverflow