008 Getting Started
源教程地址: https://www.sphinx-doc.org/en/master/usage/quickstart.html .
Sphinx is a documentation generator or a tool
that translates a set of plain text source files into various output formats,
automatically producing cross-references, indices, etc.
That is, if you have a directory containing a bunch of reStructuredText or Markdown documents,
Sphinx can generate a series of HTML files, a PDF file (via LaTeX), man pages and much more.
Sphinx focuses on documentation, in particular handwritten documentation, however, Sphinx can also be used to generate blogs, homepages and even books. Much of Sphinx’s power comes from the richness of its default plain-text markup format, reStructuredText, along with its significant extensibility capabilities.
The goal of this document is to give you a quick taste of what Sphinx is and how you might use it. When you’re done here, you can check out the installation guide followed by the intro to the default markup format used by Sphinx, reStucturedText.
For a great “introduction” to writing docs in general – the whys and hows, see also Write the docs, written by Eric Holscher.
Setting up the documentation sources
The root directory of a Sphinx collection of plain-text document sources is called the source directory.
This directory also contains the Sphinx configuration file conf.py,
where you can configure all aspects of how Sphinx reads your sources and builds your documentation.
Sphinx comes with a script called sphinx-quickstart that sets up a source directory
and creates a default conf.py with the most useful configuration values from a few questions it asks you.
To use this, run:
sphinx-quickstart
Defining document structure
Let’s assume you’ve run sphinx-quickstart.
It created a source directory with conf.py and a root document, index.rst.
The main function of the root document is to serve as a welcome page,
and to contain the root of the “table of contents tree” (or toctree).
This is one of the main things that Sphinx adds to reStructuredText,
a way to connect multiple files to a single hierarchy of documents.
The toctree directive initially is empty, and looks like so:
See also
reStructuredText directives, toctree is a reStructuredText directive, a very versatile piece of markup. Directives can have arguments, options and content. Arguments are given directly after the double colon following the directive’s name. Each directive decides whether it can have arguments, and how many. Options are given after the arguments, in form of a “field list”. The maxdepth is such an option for the toctree directive. Content follows the options or arguments after a blank line. Each directive decides whether to allow content, and what to do with it. A common gotcha with directives is that the first line of the content must be indented to the same level as the options are.
.. toctree::
:maxdepth: 2
You add documents listing them in the content of the directive:
.. toctree::
:maxdepth: 2
usage/installation
usage/quickstart
...
This is exactly how the toctree for this documentation looks. The documents to include are given as document names, which in short means that you leave off the file name extension and use forward slashes (/) as directory separators.
Read more about the toctree directive.
You can now create the files you listed in the toctree and add content, and their section titles will be inserted (up to the maxdepth level) at the place where the toctree directive is placed. Also, Sphinx now knows about the order and hierarchy of your documents. (They may contain toctree directives themselves, which means you can create deeply nested hierarchies if necessary.)
Adding content
In Sphinx source files, you can use most features of standard reStructuredText.
There are also several features added by Sphinx.
For example, you can add cross-file references in a portable way (which works for all output types) using the ref role.
For an example, if you are viewing the HTML version, you can look at the source for this document – use the “Show Source” link in the sidebar.
See reStructuredText for a more in-depth introduction to reStructuredText, including markup added by Sphinx.
Running the build
Now that you have added some files and content, let’s make a first build of the docs. A build is started with the sphinx-build program:
sphinx-build -b html sourcedir builddir
where sourcedir is the source directory,
and builddir is the directory in which you want to place the built documentation.
The -b option selects a builder; in this example Sphinx will build HTML files.
Refer to the sphinx-build man page for all options that sphinx-build supports.
However, sphinx-quickstart script creates a Makefile and a make.bat which make life even easier for you.
These can be executed by running make with the name of the builder. For example.
make html
This will build HTML docs in the build directory you chose.
Execute make without an argument to see which targets are available.
How do I generate PDF documents? make latexpdf runs the LaTeX builder and readily invokes the pdfTeX toolchain for you.
Documenting objects
One of Sphinx’s main objectives is easy documentation of objects (in a very general sense) in any domain. A domain is a collection of object types that belong together, complete with markup to create and reference descriptions of these objects.
The most prominent domain is the Python domain.
For example, to document Python’s built-in function enumerate(),
you would add this to one of your source files.
.. py:function:: enumerate(sequence[, start=0])
Return an iterator that yields tuples of an index and an item of the
*sequence*. (And so on.)
This is rendered like this:
- enumerate(sequence[, start=0])
Return an iterator that yields tuples of an index and an item of the sequence. (And so on.)
The argument of the directive is the signature of the object you describe, the content is the documentation for it. Multiple signatures can be given, each in its own line.
The Python domain also happens to be the default domain,
so you don’t need to prefix the markup with the domain name.
.. function:: enumerate(sequence[, start=0])
...
- enumerate(sequence[, start=0])
…
does the same job if you keep the default setting for the default domain.
There are several more directives for documenting other types of Python objects,
for example py:class or py:method.
There is also a cross-referencing role for each of these object types.
This markup will create a link to the documentation of enumerate().
The :py:func:`enumerate` function can be used for ...
The enumerate() function can be used for …
And here is the proof: A link to enumerate().
Again, the py: can be left out if the Python domain is the default one. It doesn’t matter which file contains the actual documentation for enumerate(); Sphinx will find it and create a link to it.
Each domain will have special rules for how the signatures can look like, and make the formatted output look pretty, or add specific features like links to parameter types, e.g. in the C/C++ domains.
See Domains for all the available domains and their directives/roles.
Basic configuration
Earlier we mentioned that the conf.py file controls how Sphinx processes your documents.
In that file, which is executed as a Python source file,
you assign configuration values. For advanced users: since it is executed by Sphinx,
you can do non-trivial tasks in it,
like extending sys.path or importing a module to find out the version you are documenting.
The config values that you probably want to change are already put into the conf.py by sphinx-quickstart
and initially commented out (with standard Python syntax: a # comments the rest of the line).
To change the default value, remove the hash sign and modify the value.
To customize a config value that is not automatically added by sphinx-quickstart,
just add an additional assignment.
Keep in mind that the file uses Python syntax for strings, numbers, lists and so on.
The file is saved in UTF-8 by default,
as indicated by the encoding declaration in the first line.
See Configuration for documentation of all available config values.
Autodoc
When documenting Python code, it is common to put a lot of documentation in the source files,
in documentation strings.
Sphinx supports the inclusion of docstrings from your modules with an extension
(an extension is a Python module that provides additional features for Sphinx projects)
called autodoc.
In order to use autodoc,
you need to activate it in conf.py by putting the string 'sphinx.ext.autodoc'
into the list assigned to the extensions config value:
extensions = ['sphinx.ext.autodoc']
Then, you have a few additional directives at your disposal.
For example, to document the function io.open(),
reading its signature and docstring from the source file, you’d write this:
.. autofunction:: io.open
- io.open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise OSError upon failure.
file is either a text or byte string giving the name (and the path if the file isn’t in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file is opened. It defaults to ‘r’ which means open for reading in text mode. Other common values are ‘w’ for writing (truncating the file if it already exists), ‘x’ for creating and writing to a new file, and ‘a’ for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:
Character
Meaning
‘r’
open for reading (default)
‘w’
open for writing, truncating the file first
‘x’
create a new file and open it for writing
‘a’
open for writing, appending to the end of the file if it exists
‘b’
binary mode
‘t’
text mode (default)
‘+’
open a disk file for updating (reading and writing)
‘U’
universal newline mode (deprecated)
The default mode is ‘rt’ (open for reading text). For binary random access, the mode ‘w+b’ opens and truncates the file to 0 bytes, while ‘r+b’ opens the file without truncation. The ‘x’ mode implies ‘w’ and raises an FileExistsError if the file already exists.
Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn’t. Files opened in binary mode (appending ‘b’ to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when ‘t’ is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
‘U’ mode is deprecated and will raise an exception in future versions of Python. It has no effect in Python 3. Use newline to control universal newlines mode.
buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:
Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.
“Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to be handled—this argument should not be used in binary mode. Pass ‘strict’ to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass ‘ignore’ to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register or run ‘help(codecs.Codec)’ for a list of the permitted encoding error strings.
newline controls how universal newlines works (it only applies to text mode). It can be None, ‘’, ‘n’, ‘r’, and ‘rn’. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in ‘n’, ‘r’, or ‘rn’, and these are translated into ‘n’ before being returned to the caller. If it is ‘’, universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
On output, if newline is None, any ‘n’ characters written are translated to the system default line separator, os.linesep. If newline is ‘’ or ‘n’, no translation takes place. If newline is any of the other legal values, any ‘n’ characters written are translated to the given string.
If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case.
A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).
open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode (‘w’, ‘r’, ‘wt’, ‘rt’, etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom.
It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode.
You can also document whole classes or even modules automatically, using member options for the auto directives, like
.. automodule:: io
:members:
The io module provides the Python interfaces to stream handling. The builtin open function is defined in this module.
At the top of the I/O hierarchy is the abstract base class IOBase. It defines the basic interface to a stream. Note, however, that there is no separation between reading and writing to streams; implementations are allowed to raise an OSError if they do not support a given operation.
Extending IOBase is RawIOBase which deals simply with the reading and writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide an interface to OS files.
BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer streams that are readable, writable, and both respectively. BufferedRandom provides a buffered interface to random access streams. BytesIO is a simple stream of in-memory bytes.
Another IOBase subclass, TextIOBase, deals with the encoding and decoding of streams into text. TextIOWrapper, which extends it, is a buffered text interface to a buffered raw stream (BufferedIOBase). Finally, StringIO is an in-memory stream for text.
Argument names are not part of the specification, and only the arguments of open() are intended to be used as keyword arguments.
data:
DEFAULT_BUFFER_SIZE
An int containing the default buffer size used by the module’s buffered I/O classes. open() uses the file’s blksize (as obtained by os.stat) if possible.
- exception io.BlockingIOError
I/O operation would block.
- class io.BufferedIOBase
Base class for buffered IO objects.
The main difference with RawIOBase is that the read() method supports omitting the size argument, and does not have a default implementation that defers to readinto().
In addition, read(), readinto() and write() may raise BlockingIOError if the underlying raw stream is in non-blocking mode and not ready; unlike their raw counterparts, they will never return None.
A typical implementation should not inherit from a RawIOBase implementation, but wrap one.
- class io.BufferedRWPair(reader, writer, buffer_size=8192, /)
A buffered reader and writer object together.
A buffered reader object and buffered writer object put together to form a sequential IO object that can read and write. This is typically used with a socket or two-way pipe.
reader and writer are RawIOBase objects that are readable and writeable respectively. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.
- close()
Flush and close the IO object.
This method has no effect if the file is already closed.
- flush()
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- isatty()
Return whether this is an ‘interactive’ stream.
Return False if it can’t be determined.
- read()
Read and return up to n bytes.
If the argument is omitted, None, or negative, reads and returns all data until EOF.
If the argument is positive, and the underlying raw stream is not ‘interactive’, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams (as well as sockets and pipes), at most one raw read will be issued, and a short result does not imply that EOF is imminent.
Returns an empty bytes object on EOF.
Returns None if the underlying raw stream was open in non-blocking mode and no data is available at the moment.
- read1()
Read and return up to n bytes, with at most one read() call to the underlying raw stream. A short result does not imply that EOF is imminent.
Returns an empty bytes object on EOF.
- readable()
Return whether object was opened for reading.
If False, read() will raise OSError.
- writable()
Return whether object was opened for writing.
If False, write() will raise OSError.
- write()
Write the given buffer to the IO stream.
Returns the number of bytes written, which is always the length of b in bytes.
Raises BlockingIOError if the buffer is full and the underlying raw stream cannot accept more data at the moment.
- class io.BufferedRandom(raw, buffer_size=8192)
A buffered interface to random access streams.
The constructor creates a reader and writer for a seekable stream, raw, given in the first argument. If the buffer_size is omitted it defaults to DEFAULT_BUFFER_SIZE.
- close()
Flush and close the IO object.
This method has no effect if the file is already closed.
- detach()
Disconnect this buffer from its underlying raw stream and return it.
After the raw stream has been detached, the buffer is in an unusable state.
- fileno()
Returns underlying file descriptor if one exists.
OSError is raised if the IO object does not use a file descriptor.
- flush()
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- isatty()
Return whether this is an ‘interactive’ stream.
Return False if it can’t be determined.
- read(size=- 1, /)
Read and return up to n bytes.
If the argument is omitted, None, or negative, reads and returns all data until EOF.
If the argument is positive, and the underlying raw stream is not ‘interactive’, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams (as well as sockets and pipes), at most one raw read will be issued, and a short result does not imply that EOF is imminent.
Returns an empty bytes object on EOF.
Returns None if the underlying raw stream was open in non-blocking mode and no data is available at the moment.
- read1(size=- 1, /)
Read and return up to n bytes, with at most one read() call to the underlying raw stream. A short result does not imply that EOF is imminent.
Returns an empty bytes object on EOF.
- readable()
Return whether object was opened for reading.
If False, read() will raise OSError.
- readline(size=- 1, /)
Read and return a line from the stream.
If size is specified, at most size bytes will be read.
The line terminator is always b’n’ for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized.
- seek(target, whence=0, /)
Change stream position.
Change the stream position to the given byte offset. The offset is interpreted relative to the position indicated by whence. Values for whence are:
0 – start of stream (the default); offset should be zero or positive
1 – current stream position; offset may be negative
2 – end of stream; offset is usually negative
Return the new absolute position.
- seekable()
Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().
- tell()
Return current stream position.
- truncate(pos=None, /)
Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO position as reported by tell(). Returns the new size.
- writable()
Return whether object was opened for writing.
If False, write() will raise OSError.
- write(buffer, /)
Write the given buffer to the IO stream.
Returns the number of bytes written, which is always the length of b in bytes.
Raises BlockingIOError if the buffer is full and the underlying raw stream cannot accept more data at the moment.
- class io.BufferedReader(raw, buffer_size=8192)
Create a new buffered reader using the given readable raw IO object.
- close()
Flush and close the IO object.
This method has no effect if the file is already closed.
- detach()
Disconnect this buffer from its underlying raw stream and return it.
After the raw stream has been detached, the buffer is in an unusable state.
- fileno()
Returns underlying file descriptor if one exists.
OSError is raised if the IO object does not use a file descriptor.
- flush()
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- isatty()
Return whether this is an ‘interactive’ stream.
Return False if it can’t be determined.
- read(size=- 1, /)
Read and return up to n bytes.
If the argument is omitted, None, or negative, reads and returns all data until EOF.
If the argument is positive, and the underlying raw stream is not ‘interactive’, multiple raw reads may be issued to satisfy the byte count (unless EOF is reached first). But for interactive raw streams (as well as sockets and pipes), at most one raw read will be issued, and a short result does not imply that EOF is imminent.
Returns an empty bytes object on EOF.
Returns None if the underlying raw stream was open in non-blocking mode and no data is available at the moment.
- read1(size=- 1, /)
Read and return up to n bytes, with at most one read() call to the underlying raw stream. A short result does not imply that EOF is imminent.
Returns an empty bytes object on EOF.
- readable()
Return whether object was opened for reading.
If False, read() will raise OSError.
- readline(size=- 1, /)
Read and return a line from the stream.
If size is specified, at most size bytes will be read.
The line terminator is always b’n’ for binary files; for text files, the newlines argument to open can be used to select the line terminator(s) recognized.
- seek(target, whence=0, /)
Change stream position.
Change the stream position to the given byte offset. The offset is interpreted relative to the position indicated by whence. Values for whence are:
0 – start of stream (the default); offset should be zero or positive
1 – current stream position; offset may be negative
2 – end of stream; offset is usually negative
Return the new absolute position.
- seekable()
Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().
- tell()
Return current stream position.
- truncate(pos=None, /)
Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO position as reported by tell(). Returns the new size.
- class io.BufferedWriter(raw, buffer_size=8192)
A buffer for a writeable sequential RawIO object.
The constructor creates a BufferedWriter for the given writeable raw stream. If the buffer_size is not given, it defaults to DEFAULT_BUFFER_SIZE.
- close()
Flush and close the IO object.
This method has no effect if the file is already closed.
- detach()
Disconnect this buffer from its underlying raw stream and return it.
After the raw stream has been detached, the buffer is in an unusable state.
- fileno()
Returns underlying file descriptor if one exists.
OSError is raised if the IO object does not use a file descriptor.
- flush()
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- isatty()
Return whether this is an ‘interactive’ stream.
Return False if it can’t be determined.
- seek(target, whence=0, /)
Change stream position.
Change the stream position to the given byte offset. The offset is interpreted relative to the position indicated by whence. Values for whence are:
0 – start of stream (the default); offset should be zero or positive
1 – current stream position; offset may be negative
2 – end of stream; offset is usually negative
Return the new absolute position.
- seekable()
Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().
- tell()
Return current stream position.
- truncate(pos=None, /)
Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO position as reported by tell(). Returns the new size.
- writable()
Return whether object was opened for writing.
If False, write() will raise OSError.
- write(buffer, /)
Write the given buffer to the IO stream.
Returns the number of bytes written, which is always the length of b in bytes.
Raises BlockingIOError if the buffer is full and the underlying raw stream cannot accept more data at the moment.
- class io.BytesIO(initial_bytes=b'')
Buffered I/O implementation using an in-memory bytes buffer.
- close()
Disable all I/O operations.
- closed
True if the file is closed.
- flush()
Does nothing.
- getbuffer()
Get a read-write view over the contents of the BytesIO object.
- getvalue()
Retrieve the entire contents of the BytesIO object.
- isatty()
Always returns False.
BytesIO objects are not connected to a TTY-like device.
- read(size=- 1, /)
Read at most size bytes, returned as a bytes object.
If the size argument is negative, read until EOF is reached. Return an empty bytes object at EOF.
- read1(size=- 1, /)
Read at most size bytes, returned as a bytes object.
If the size argument is negative or omitted, read until EOF is reached. Return an empty bytes object at EOF.
- readable()
Returns True if the IO object can be read.
- readinto(buffer, /)
Read bytes into buffer.
Returns number of bytes read (0 for EOF), or None if the object is set not to block and has no data to read.
- readline(size=- 1, /)
Next line from the file, as a bytes object.
Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty bytes object at EOF.
- readlines(size=None, /)
List of bytes objects, each a line from the file.
Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned.
- seek(pos, whence=0, /)
Change stream position.
- Seek to byte offset pos relative to position indicated by whence:
0 Start of stream (the default). pos should be >= 0; 1 Current position - pos may be negative; 2 End of stream - pos usually negative.
Returns the new absolute position.
- seekable()
Returns True if the IO object can be seeked.
- tell()
Current file position, an integer.
- truncate(size=None, /)
Truncate the file to at most size bytes.
Size defaults to the current file position, as returned by tell(). The current file position is unchanged. Returns the new size.
- writable()
Returns True if the IO object can be written.
- write(b, /)
Write bytes to file.
Return the number of bytes written.
- writelines(lines, /)
Write lines to the file.
Note that newlines are not added. lines can be any iterable object producing bytes-like objects. This is equivalent to calling write() for each element.
- class io.FileIO(file, mode='r', closefd=True, opener=None)
Open a file.
The mode can be ‘r’ (default), ‘w’, ‘x’ or ‘a’ for reading, writing, exclusive creation or appending. The file will be created if it doesn’t exist when opened for writing or appending; it will be truncated when opened for writing. A FileExistsError will be raised if it already exists when opened for creating. Opening a file for creating implies writing so this mode behaves in a similar way to ‘w’.Add a ‘+’ to the mode to allow simultaneous reading and writing. A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (name, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).
- close()
Close the file.
A closed file cannot be used for further I/O operations. close() may be called more than once without error.
- closed
True if the file is closed
- closefd
True if the file descriptor will be closed by close().
- fileno()
Return the underlying file descriptor (an integer).
- isatty()
True if the file is connected to a TTY device.
- mode
String giving the file mode
- read(size=- 1, /)
Read at most size bytes, returned as bytes.
Only makes one system call, so less data may be returned than requested. In non-blocking mode, returns None if no data is available. Return an empty bytes object at EOF.
- readable()
True if file was opened in a read mode.
- readall()
Read all data from the file, returned as bytes.
In non-blocking mode, returns as much as is immediately available, or None if no data is available. Return an empty bytes object at EOF.
- readinto(buffer, /)
Same as RawIOBase.readinto().
- seek(pos, whence=0, /)
Move to new file position and return the file position.
Argument offset is a byte count. Optional argument whence defaults to SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values are SEEK_CUR or 1 (move relative to current position, positive or negative), and SEEK_END or 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file).
Note that not all file objects are seekable.
- seekable()
True if file supports random-access.
- tell()
Current file position.
Can raise OSError for non seekable files.
- truncate(size=None, /)
Truncate the file to at most size bytes and return the truncated size.
Size defaults to the current file position, as returned by tell(). The current file position is changed to the value of size.
- writable()
True if file was opened in a write mode.
- write(b, /)
Write buffer b to file, return number of bytes written.
Only makes one system call, so not all of the data may be written. The number of bytes actually written is returned. In non-blocking mode, returns None if the write would block.
- class io.IOBase
The abstract base class for all I/O classes.
This class provides dummy implementations for many methods that derived classes can override selectively; the default implementations represent a file that cannot be read, written or seeked.
Even though IOBase does not declare read, readinto, or write because their signatures will vary, implementations and clients should consider those methods part of the interface. Also, implementations may raise UnsupportedOperation when operations they do not support are called.
The basic type used for binary data read from or written to a file is bytes. Other bytes-like objects are accepted as method arguments too. In some cases (such as readinto), a writable object is required. Text I/O classes work with str data.
Note that calling any method (except additional calls to close(), which are ignored) on a closed stream should raise a ValueError.
IOBase (and its subclasses) support the iterator protocol, meaning that an IOBase object can be iterated over yielding the lines in a stream.
IOBase also supports the
withstatement. In this example, fp is closed after the suite of the with statement is complete:- with open(‘spam.txt’, ‘r’) as fp:
fp.write(‘Spam and eggs!’)
- class io.RawIOBase
Base class for raw binary I/O.
- class io.StringIO(initial_value='', newline='\n')
Text I/O implementation using an in-memory buffer.
The initial_value argument sets the value of object. The newline argument is like the one of TextIOWrapper’s constructor.
- close()
Close the IO object.
Attempting any further operation after the object is closed will raise a ValueError.
This method has no effect if the file is already closed.
- getvalue()
Retrieve the entire contents of the object.
- newlines
- read(size=- 1, /)
Read at most size characters, returned as a string.
If the argument is negative or omitted, read until EOF is reached. Return an empty string at EOF.
- readable()
Returns True if the IO object can be read.
- readline(size=- 1, /)
Read until newline or EOF.
Returns an empty string if EOF is hit immediately.
- seek(pos, whence=0, /)
Change stream position.
- Seek to character offset pos relative to position indicated by whence:
0 Start of stream (the default). pos should be >= 0; 1 Current position - pos must be 0; 2 End of stream - pos must be 0.
Returns the new absolute position.
- seekable()
Returns True if the IO object can be seeked.
- tell()
Tell the current file position.
- truncate(pos=None, /)
Truncate size to pos.
The pos argument defaults to the current file position, as returned by tell(). The current file position is unchanged. Returns the new absolute position.
- writable()
Returns True if the IO object can be written.
- write(s, /)
Write string to file.
Returns the number of characters written, which is always equal to the length of the string.
- class io.TextIOBase
Base class for text I/O.
This class provides a character and line based interface to stream I/O. There is no readinto method because Python’s character strings are immutable.
- class io.TextIOWrapper(buffer, encoding=None, errors=None, newline=None, line_buffering=False, write_through=False)
Character and line based layer over a BufferedIOBase object, buffer.
encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False).
errors determines the strictness of encoding and decoding (see help(codecs.Codec) or the documentation for codecs.register) and defaults to “strict”.
newline controls how line endings are handled. It can be None, ‘’, ‘n’, ‘r’, and ‘rn’. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in ‘n’, ‘r’, or ‘rn’, and these are translated into ‘n’ before being returned to the caller. If it is ‘’, universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
On output, if newline is None, any ‘n’ characters written are translated to the system default line separator, os.linesep. If newline is ‘’ or ‘n’, no translation takes place. If newline is any of the other legal values, any ‘n’ characters written are translated to the given string.
If line_buffering is True, a call to flush is implied when a call to write contains a newline character.
- close()
Flush and close the IO object.
This method has no effect if the file is already closed.
- detach()
Separate the underlying buffer from the TextIOBase and return it.
After the underlying buffer has been detached, the TextIO is in an unusable state.
- encoding
- errors
- fileno()
Returns underlying file descriptor if one exists.
OSError is raised if the IO object does not use a file descriptor.
- flush()
Flush write buffers, if applicable.
This is not implemented for read-only and non-blocking streams.
- isatty()
Return whether this is an ‘interactive’ stream.
Return False if it can’t be determined.
- newlines
- read(size=- 1, /)
Read at most n characters from stream.
Read from underlying buffer until we have n characters or we hit EOF. If n is negative or omitted, read until EOF.
- readable()
Return whether object was opened for reading.
If False, read() will raise OSError.
- readline(size=- 1, /)
Read until newline or EOF.
Returns an empty string if EOF is hit immediately.
- reconfigure(*, encoding=None, errors=None, newline=None, line_buffering=None, write_through=None)
Reconfigure the text stream with new parameters.
This also does an implicit stream flush.
- seek(cookie, whence=0, /)
Change stream position.
Change the stream position to the given byte offset. The offset is interpreted relative to the position indicated by whence. Values for whence are:
0 – start of stream (the default); offset should be zero or positive
1 – current stream position; offset may be negative
2 – end of stream; offset is usually negative
Return the new absolute position.
- seekable()
Return whether object supports random access.
If False, seek(), tell() and truncate() will raise OSError. This method may need to do a test seek().
- tell()
Return current stream position.
- truncate(pos=None, /)
Truncate file to size bytes.
File pointer is left unchanged. Size defaults to the current IO position as reported by tell(). Returns the new size.
- writable()
Return whether object was opened for writing.
If False, write() will raise OSError.
- write(text, /)
Write string to stream. Returns the number of characters written (which is always equal to the length of the string).
- exception io.UnsupportedOperation
- io.open(file, mode='r', buffering=- 1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Open file and return a stream. Raise OSError upon failure.
file is either a text or byte string giving the name (and the path if the file isn’t in the current working directory) of the file to be opened or an integer file descriptor of the file to be wrapped. (If a file descriptor is given, it is closed when the returned I/O object is closed, unless closefd is set to False.)
mode is an optional string that specifies the mode in which the file is opened. It defaults to ‘r’ which means open for reading in text mode. Other common values are ‘w’ for writing (truncating the file if it already exists), ‘x’ for creating and writing to a new file, and ‘a’ for appending (which on some Unix systems, means that all writes append to the end of the file regardless of the current seek position). In text mode, if encoding is not specified the encoding used is platform dependent: locale.getpreferredencoding(False) is called to get the current locale encoding. (For reading and writing raw bytes use binary mode and leave encoding unspecified.) The available modes are:
Character
Meaning
‘r’
open for reading (default)
‘w’
open for writing, truncating the file first
‘x’
create a new file and open it for writing
‘a’
open for writing, appending to the end of the file if it exists
‘b’
binary mode
‘t’
text mode (default)
‘+’
open a disk file for updating (reading and writing)
‘U’
universal newline mode (deprecated)
The default mode is ‘rt’ (open for reading text). For binary random access, the mode ‘w+b’ opens and truncates the file to 0 bytes, while ‘r+b’ opens the file without truncation. The ‘x’ mode implies ‘w’ and raises an FileExistsError if the file already exists.
Python distinguishes between files opened in binary and text modes, even when the underlying operating system doesn’t. Files opened in binary mode (appending ‘b’ to the mode argument) return contents as bytes objects without any decoding. In text mode (the default, or when ‘t’ is appended to the mode argument), the contents of the file are returned as strings, the bytes having been first decoded using a platform-dependent encoding or using the specified encoding if given.
‘U’ mode is deprecated and will raise an exception in future versions of Python. It has no effect in Python 3. Use newline to control universal newlines mode.
buffering is an optional integer used to set the buffering policy. Pass 0 to switch buffering off (only allowed in binary mode), 1 to select line buffering (only usable in text mode), and an integer > 1 to indicate the size of a fixed-size chunk buffer. When no buffering argument is given, the default buffering policy works as follows:
Binary files are buffered in fixed-size chunks; the size of the buffer is chosen using a heuristic trying to determine the underlying device’s “block size” and falling back on io.DEFAULT_BUFFER_SIZE. On many systems, the buffer will typically be 4096 or 8192 bytes long.
“Interactive” text files (files for which isatty() returns True) use line buffering. Other text files use the policy described above for binary files.
encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings.
errors is an optional string that specifies how encoding errors are to be handled—this argument should not be used in binary mode. Pass ‘strict’ to raise a ValueError exception if there is an encoding error (the default of None has the same effect), or pass ‘ignore’ to ignore errors. (Note that ignoring encoding errors can lead to data loss.) See the documentation for codecs.register or run ‘help(codecs.Codec)’ for a list of the permitted encoding error strings.
newline controls how universal newlines works (it only applies to text mode). It can be None, ‘’, ‘n’, ‘r’, and ‘rn’. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in ‘n’, ‘r’, or ‘rn’, and these are translated into ‘n’ before being returned to the caller. If it is ‘’, universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
On output, if newline is None, any ‘n’ characters written are translated to the system default line separator, os.linesep. If newline is ‘’ or ‘n’, no translation takes place. If newline is any of the other legal values, any ‘n’ characters written are translated to the given string.
If closefd is False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given and must be True in that case.
A custom opener can be used by passing a callable as opener. The underlying file descriptor for the file object is then obtained by calling opener with (file, flags). opener must return an open file descriptor (passing os.open as opener results in functionality similar to passing None).
open() returns a file object whose type depends on the mode, and through which the standard file operations such as reading and writing are performed. When open() is used to open a file in a text mode (‘w’, ‘r’, ‘wt’, ‘rt’, etc.), it returns a TextIOWrapper. When used to open a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom.
It is also possible to use a string or bytearray as a file for both reading and writing. For strings StringIO can be used like a file opened in a text mode, and for bytes a BytesIO can be used like a file opened in a binary mode.
- io.open_code(path)
Opens the provided file with the intent to import the contents.
This may perform extra validation beyond open(), but is otherwise interchangeable with calling open(path, ‘rb’).
autodoc needs to import your modules in order to extract the docstrings.
Therefore, you must add the appropriate path to sys.path in your conf.py.
Warning
autodoc imports the modules to be documented. If any modules have side effects on import, these will be executed by autodoc when sphinx-build is run.
If you document scripts (as opposed to library modules),
make sure their main routine is protected by a if __name__ == '__main__' condition.
See sphinx.ext.autodoc for the complete description of the features of autodoc.
Intersphinx
Many Sphinx documents including the Python documentation are published on the Internet.
When you want to make links to such documents from your documentation,
you can do it with sphinx.ext.intersphinx.
In order to use intersphinx,
you need to activate it in conf.py by putting
the string 'sphinx.ext.intersphinx' into the extensions list
and set up the intersphinx_mapping config value.
For example, to link to io.open() in the Python library manual,
you need to setup your intersphinx_mapping like:
intersphinx_mapping = {'python': ('https://docs.python.org/3', None)}
And now, you can write a cross-reference like :py:func:`io.open` (io.open()).
Any cross-reference that has no matching target in the current documentation set,
will be looked up in the documentation sets configured in intersphinx_mapping
(this needs access to the URL in order to download the list of valid targets).
Intersphinx also works for some other domain’s roles including :ref:,
however it doesn’t work for :doc: as that is non-domain role.
See sphinx.ext.intersphinx for the complete description of the features of intersphinx.
More topics to be covered
Other extensions: https://www.sphinx-doc.org/en/master/usage/extensions/index.html .
Static files:
Selecting a theme: https://www.sphinx-doc.org/en/master/usage/theming.html .
Setuptools integration: https://www.sphinx-doc.org/en/master/usage/advanced/setuptools.html .
Templating: https://www.sphinx-doc.org/en/master/development/templating.html#templating .
Using extensions:
Writing extensions: https://www.sphinx-doc.org/en/master/extdev/index.html#dev-extensions .