Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>") 
like image 854
thias Avatar asked Oct 17 '11 09:10

thias


People also ask

How do you print a docstring in a function?

Try: class MyClass(): # ... def my_function(self): """Docstring for my function""" print MyClass. my_function.

How do you display the docstring for a function in Python?

Docstrings are accessible from the doc attribute (__doc__) for any of the Python objects and also with the built-in help() function. An object's docstring is defined by including a string constant as the first statement in the object's definition.

How do I view a docstring?

All functions should have a docstring. Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.

What is print (__ doc __)?

The print(__doc__) command simply re-uses that documentation string to write it to your terminal each time you run the script, and any other python tool (like the interactive interpreter help() function, for example) can introspect that same value.


2 Answers

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.

like image 173
Petr Viktorin Avatar answered Sep 25 '22 01:09

Petr Viktorin


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) 
like image 21
wint3rschlaefer Avatar answered Sep 24 '22 01:09

wint3rschlaefer