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

thias picture thias · Oct 17, 2011 · Viewed 31.5k times · Source

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

Answer

Petr Viktorin picture Petr Viktorin · Oct 17, 2011

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.