Within the Python shell if I were to type the following code
import pydoc
pydoc.help(print)
ot would return info on the print function.
Now if I wanted to access this module outside the Python shell, for example in either PowerShell or the Command Prompt in Windows, I would type the following command:
python -m pydoc print
which returns the same info as the previous command that I typed.
Now I understand that within the Python shell that .help
is a method of pydoc
that I call with a parameter of print
. Outside the shell with python -m
it's specifying to run a Python module (in this case pydoc
).
But what confuses me is how does pydoc
know what to do with the print
parameter? How does it know which method to use?
CodePudding user response:
When you run a script as a top level module (which is what happens when you do python -m pydoc print
) its __name__
will be "__main__"
- thus the very common piece of code: if __name__ == '__main__'
- this if
will not be true when importing the module, so anything in it will not execute.
Now that we know how to detect when a module is run as a top level, we can write a piece of code that will do things like take CLI arguments using standard methods of sys.argv
etc. and put it after mentioned if
and we have our own behaviour for python -m <module-name> <arguments>
CodePudding user response:
Pydoc is a documentation library that generates documentation from Python modules. From the documentation
For modules, classes, functions and methods, the displayed documentation is derived from the docstring (i.e. the
__doc__
attribute) of the object, and recursively of its documentable members. If there is no docstring, pydoc tries to obtain a description from the block of comment lines just above the definition of the class, function or method in the source file, or at the top of the module.
So basically, you can say that pydoc
tries to use the documentation provided by the module's methods themselves, or if it does not find a docstring, it tries to read the comments above these module's methods. Finally, it does this for all the methods, classes, functions, parameters inside a module, and prints it to the terminal, or browser.