How can I print a Python file's docstring when executing it?
Solution 1:
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:
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)