Search code examples
pythondocstring

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


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>")

Solution

  • 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.