Learn the Python help() function and pydoc | Python for
Beginners (4:52)
Code Examples and Video Script
Welcome. Today's question: How do you find help in Python using
help() and
pydoc?
I'm Paul, and one of the most frustrating things for budding
programmers is how much time is spent finding help.
So here I'll cover several resources, zipping through what can be found
at the Linux command line using
python3, then python.org, then
Python's built-in help() and
pydoc3 accessed from the Linux
command line, before heading to the next tutorial on keywords.
(Commands in Linux)
pydoc3
whatis
man
python3
clear
(Functions in Python)
help()
exit()
Step 1 - Find Help With the python3 Command
Let's jump to the Terminal, and part of my goal with these sub-5-minute
summaries, is to keep what we've done fresh. Let's do a
quick whatis to summarize Linux
commands we'll use here.
paul@fullstack:~$ whatis pydoc3 whatis man python3 clear
pydoc3 (1) - the Python documentation tool
whatis (1) - display one-line manual page descriptions
man (1) - an interface to the on-line reference manual
man (7) - macros to format man pages
python3 (1) - an interpreted, interactive, object-oriented programming language
clear (1) - clear the terminal screen
Find a summary of python3 command options
The -h summary for
python3 covers syntax and options for
customizing startup for the Python environment.
paul@fullstack:~$ python3 -h
usage: python3 [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b : issue warnings about str(bytes_instance), str(bytearray_instance)
and comparing bytes/bytearray with str. (-bb: issue errors)
-B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser; also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO : remove doc-strings in addition to the -O optimizations
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S : don't imply 'import site' on initialization
-u : unbuffered binary stdout and stderr, stdin always buffered;
also PYTHONUNBUFFERED=x
see man page for details on internal buffering relating to '-u'
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH : ':'-separated list of directories prefixed to the
default module search path. The result is sys.path.
PYTHONHOME : alternate <prefix> directory (or <prefix>:<exec_prefix>).
The default module search path uses <prefix>/pythonX.X.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
to seed the hashes of str, bytes and datetime objects. It can also be
set to an integer in the range [0,4294967295] to get hash values with a
predictable seed.
Find your Python version number
Plus this one for the version number.
paul@fullstack:~$ python3 -V
Python 3.4.2
Access the python3 man page
And then, like any command in Linux, the
man page goes into more detail.
paul@fullstack:~$ man python3
As I browse, I will say that while help in Linux isn't pretty, it is
easy to navigate. It's local so it goes with you, and it's extremely
useful once you get the hang of it.
PYTHON(1) General Commands Manual PYTHON(1)
NAME
python - an interpreted, interactive, object-oriented programming language
SYNOPSIS
python [ -B ] [ -b ] [ -d ] [ -E ] [ -h ] [ -i ] [ -I ]
[ -m module-name ] [ -q ] [ -O ] [ -OO ] [ -s ] [ -S ] [ -u ]
[ -v ] [ -V ] [ -W argument ] [ -x ] [ [ -X option ] -? ]
[ -c command | script | - ] [ arguments ]
DESCRIPTION
Python is an interpreted, interactive, object-oriented programming language that
combines remarkable power with very clear syntax. For an introduction to program
ming in Python you are referred to the Python Tutorial. The Python Library Refer
ence documents built-in and standard types, constants, functions and modules.
Finally, the Python Reference Manual describes the syntax and semantics of the core
language in (perhaps too) much detail. (These documents may be located via the
INTERNET RESOURCES below; they may be installed on your system as well.)
Python's basic power can be extended with your own modules written in C or C++. On
most systems such modules may be dynamically loaded. Python is also adaptable as an
extension language for existing applications. See the internal documentation for
hints.
Documentation for installed Python modules and packages can be viewed by running the
pydoc program.
Manual page python3 (1) line 1 (press h for help or q to quit)
I am a huge convert. I love the fact that it's there, it's consistently
formatted and you won't get inundated with annoying ad banners.
Step 2 - Find Documentation on python.org
I should also point you to https://www.python.org/doc/versions/ here, because
every version has its own set of documentation, and a link is provided.
Step 3 - Using the Python help() Function
Now for help that sits in Python, which is referenced right when you
launch. Here is a trick, it can be accessed two ways.
Let's type help and notice how it
refers to interactive help and object help?
paul@fullstack:~$ python3
Python 3.4.2 (default, Oct 8 2014, 10:45:20)
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> help
Type help() for interactive help, or help(object) for help about object.
>>>
Using Python interactive help
Let's try interactive help first.
>>> help()
Welcome to Python 3.4's help utility!
If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.4/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type "quit".
To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics". Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
help> modules
You can read this later. It basically says that in interactive
mode, identified when the command prompt changes here
(to help>). You can type
modules for a list of modules
installed.
_random dummy_threading plistlib turtle
_sha1 email poplib types
_sha256 encodings posix unicodedata
_sha512 enum posixpath unittest
_sitebuiltins errno pprint urllib
_socket faulthandler profile uu
_sqlite3 fcntl pstats uuid
_sre filecmp pty venv
_ssl fileinput pwd warnings
_stat fnmatch py_compile wave
_string formatter pyclbr weakref
_strptime fpectl pydoc webbrowser
_struct fractions pydoc_data wsgiref
_symtable tfplib pyexpat xdrlib
_sysconfigdata funtools queue xml
_sysconfigdata_m gc quopri xmlrpc
_testbuffer genericpath random xxlimited
_testcapi getopt re xxsubtype
_testimportmultiple getpass readline zipfile
_thread gettext reprlib zipimport
_threading_local glob resource zlib
_tracemalloc grp rlcompleter
_warnings gzip runpy
_weakref hashlib sched
Enter any module name to get more help. Or, type "module spam" to search
for modules whose name or summary contain the string "spam".
help> random
Let's pick one, a random one and notice
how it looks a lot like a Linux man
page. That's comforting.
Help on module random:
NAME
random - Random variable generators.
MODULE REFERENCE
http://docs.python.org/3.4/library/random
The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.
DESCRIPTION
integers
--------
uniform within range
sequences
---------
pick random element
pick random sample
generate random permutation
distribution on the real line:
-----------------------------
uniform
:
Also, if you don't like lifting your hands off the keys,
j scrolls down and
k scrolls up like in other programs
(ie. less and
man).
Hit q to return to the help prompt.
Interactive help also said we could type "keywords", "symbols" or
"topics".
help> keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass
Pretty handy huh?
Type quit to quit, and
help because we should cover object
mode.
help> quit
You are now leaving help and returning to the Python interpreter.
If you want to ask for help on a particular object directly from the
interpreter, you can type "help(object)". Executing "help('string')"
has the same effect as typing a particular string at the help> prompt.
>>>
Now we're at the Python interpreter. Notice the signature three
greater than signs?
Using Python object help
Here we can access the same documentation we just accessed using
help('keywords') inside single
quotes.
>>> help('keywords')
Here is a list of the Python keywords. Enter any keyword to get more help.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass
Or just input an object, like the function we used in the
last tutorial, round.
>>> help(round)
Help on built-in function round in module builtins:
round(...)
round(number[, ndigits]) -> number
Round a number to a given precision in decimal digits (default 0 digits)
This returns an int when called with one argument, otherwise the
same type as the number. ndigits may be negative.
(END)
Hit q and
exit().
>>> exit()
paul@fullstack:~$
Is this confusing? Yes, certainly. We started at the Linux command
line, then inside a Python interpreter, and within that, interactive
help and now we're back to Linux.
I suggest playing with it, get lost like we just did and find a path
that works for you.
Step 4 - Find Python Help With pydoc
Let's move on to pydoc3, accessing it
from Linux, but first with the
-h option, giving a summary.
Using the pydoc -h summary
paul@fullstack:~$ pydoc3 -h
pydoc - the Python documentation tool
pydoc3 <name> ...
Show text documentation on something. <name> may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package. If <name> contains a '/', it is used as the path to a
Python source file to document. If name is 'keywords', 'topics',
or 'modules', a listing of these things is displayed.
pydoc3 -k <keyword>
Search for a keyword in the synopsis lines of all available modules.
pydoc3 -p <port>
Start an HTTP server on the given port on the local machine. Port
number 0 can be used to get an arbitrary unused port.
pydoc3 -b
Start an HTTP server on an arbitrary unused port and open a Web browser
to interactively browse documentation. The -p option can be used with
the -b option to explicitly specify the server port.
pydoc3 -w <name> ...
Write out the HTML documentation for a module to a file in the current
directory. If <name> contains a '/', it is treated as a filename; if
it names a directory, documentation is written for all the contents.
paul@fullstack:~$
Using man pydoc3
Also, the man page for more detail.
paul@fullstack:~$ man pydoc3
PYDOC3.4(1) General Commands Manual PYDOC3.4(1)
NAME
pydoc3.4 - the Python documentation tool
SYNOPSIS
pydoc3.4 name
pydoc3.4 -k keyword
pydoc3.4 -p port
pydoc3.4 -g
pydoc3.4 -w module [...]
DESCRIPTION
pydoc3.4 name Show text documentation on something. name may be the name of a
Python keyword, topic, function, module, or package, or a dotted reference to a
class or function within a module or module in a package. If name contains a '/',
it is used as the path to a Python source file to document. If name is 'keywords',
'topics', or 'modules', a listing of these things is displayed.
pydoc3.4 -k keyword Search for a keyword in the synopsis lines of all available mod
ules.
pydoc3.4 -p port Start an HTTP server on the given port on the local machine.
pydoc3.4 -g Pop up a graphical interface for finding and serving documentation.
pydoc3.4 -w name [...] Write out the HTML documentation for a module to a file in
the current directory. If name contains a '/', it is treated as a filename; if it
names a directory, documentation is written for all the contents.
AUTHOR
Moshe Zadka, based on "pydoc --help"
PYDOC3.4(1)
Manual page for pydoc3(1) line 1 (press h for help or q to quit)
Using pydoc3 without options or arguments
And pydoc3 is the same as
pydoc3 -h.
paul@fullstack:~$ pydoc3
pydoc - the Python documentation tool
pydoc3 <name> ...
Show text documentation on something. <name> may be the name of a
Python keyword, topic, function, module, or package, or a dotted
reference to a class or function within a module or module in a
package. If <name> contains a '/', it is used as the path to a
Python source file to document. If name is 'keywords', 'topics',
or 'modules', a listing of these things is displayed.
pydoc3 -k <keyword>
Search for a keyword in the synopsis lines of all available modules.
pydoc3 -p <port>
Start an HTTP server on the given port on the local machine. Port
number 0 can be used to get an arbitrary unused port.
pydoc3 -b
Start an HTTP server on an arbitrary unused port and open a Web browser
to interactively browse documentation. The -p option can be used with
the -b option to explicitly specify the server port.
pydoc3 -w <name> ...
Write out the HTML documentation for a module to a file in the current
directory. If <name> contains a '/', it is treated as a filename; if
it names a directory, documentation is written for all the contents.
paul@fullstack:~$
We will walk through all five here.
Using pydoc3 <name>
The first one, we could type pydoc3
and keywords, like earlier.
paul@fullstack:~$ pydoc3 keywords
Here is a list of the Python keywords. Enter any keyword to get more help.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not
class from or
continue global pass
Using pydoc3 -k <keyword>
The second option -k is like
-k in
man pages, used to search names
and description fields, so try
pydoc3 -k html.
paul@fullstack:~$ pydoc3 -k html
_markupbase - Shared support for scanning document type declarations in HTML and XHTML.
html - General functions for HTML manipulation.
html.entities - HTML character entity references.
html.parser - A parser for HTML and XHTML.
pydoc - Generate Python documentation in HTML or text for interactive use.
Using pydoc3 -p <port> and pydoc3 -b
The -p and
-b options show web pages on your
local GUI-based Linux, Mac or Windows computer. Recall I'm using the
SSH protocol to view the server in this window, so I can't show you
these.
Using pydoc3 -w <name>
The fifth option -w, is a bit out of
our scope here in Python for Beginners, so we'll return to it later.
With it you can create documentation from what's called a (Python)
docstring, which is like a comment.
The difference between pydoc and pydoc3
Oh and for the curious, pydoc without
the 3 leads to (Python) version 2 docs.
paul@fullstack:~$ whatis pydoc pydoc3
pydoc (1) - the Python documentation tool
pydoc3 (1) - the Python documentation tool
Step 5 - Next: Keywords in Python
I must say, I find it odd that other videos and books don't show
beginners how to help themselves, but we have lofty goals here, and
you won't make it unless you can find help quickly.
Client : HTML, CSS, JavaScript
Software : Python Scientific Stack
Data : PostgreSQL, MySQL
OS : Linux (command line), Debian
I hope this helped, and if it did, please subscribe and hang in there
for the next tutorial on keywords.
Have a nice day.
What's Next?
See other free opportunities to learn at our YouTube Channel.
To access all tutorials, click Outline.
To learn about Python math functions, click Back.
Alms for the pour, click Tip.
For an introduction to Python keywords, click Next.