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?
#!/usr/bin/env python """ Usage: script.py This describes the script. """ import sys if len(sys.argv) < 2: print("<here comes the docstring>")
Try: class MyClass(): # ... def my_function(self): """Docstring for my function""" print MyClass. my_function.
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.
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.
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With