Isolating Extension Modules

Isolating Extension Modules¶
Who should read this¶
This guide is written for maintainers of C-API extensions who would like to make that extension safer to use in applications where Python itself is used as a library.
Background¶
An interpreter is the context in which Python code runs. It contains configuration (e.g. the import path) and runtime state (e.g. the set of imported modules).
Python supports running multiple interpreters in one process. There are two cases to think about—users may run interpreters:
in sequence, with several
Py_InitializeEx()
/Py_FinalizeEx()
cycles, andin parallel, managing “sub-interpreters” using
Py_NewInterpreter()
/Py_EndInterpreter()
.
Both cases (and combinations of them) would be most useful when embedding Python within a library. Libraries generally shouldn’t make assumptions about the application that uses them, which include assuming a process-wide “main Python interpreter”.
Historically, Python extension modules don’t handle this use case well.
Many extension modules (and even some stdlib modules) use per-process
global state, because C static
variables are extremely easy to use.
Thus, data that should be specific to an interpreter ends up being shared
between interpreters. Unless the extension developer is careful, it is very
easy to introduce edge cases that lead to crashes when a module is loaded in
more than one interpreter in the same process.
Unfortunately, per-interpreter state is not easy to achieve. Extension authors tend to not keep multiple interpreters in mind when developing, and it is currently cumbersome to test the behavior.
Enter Per-Module State¶
Instead of focusing on per-interpreter state, Python’s C API is evolving to better support the more granular per-module state. This means that C-level data should be attached to a module object. Each interpreter creates its own module object, keeping the data separate. For testing the isolation, multiple module objects corresponding to a single extension can even be loaded in a single interpreter.
Per-module state provides an easy way to think about lifetime and resource ownership: the extension module will initialize when a module object is created, and clean up when it’s freed. In this regard, a module is just like any other PyObject*; there are no “on interpreter shutdown” hooks to think—or forget—about.
Note that there are use cases for different kinds of “globals”: per-process, per-interpreter, per-thread or per-task state. With per-module state as the default, these are still possible, but you should treat them as exceptional cases: if you need them, you should give them additional care and testing. (Note that this guide does not cover them.)
Isolated Module Objects¶
The key point to keep in mind when developing an extension module is that several module objects can be created from a single shared library. For example:
>>> import sys
>>> import binascii
>>> old_binascii = binascii
>>> del sys.modules['binascii']
>>> import binascii # create a new module object
>>> old_binascii == binascii
False
As a rule of thumb, the two modules should be completely independent. All objects and state specific to the module should be encapsulated within the module object, not shared with other module objects, and cleaned up when the module object is deallocated. Since this just is a rule of thumb, exceptions are possible (see Managing Global State), but they will need more thought and attention to edge cases.
While some modules could do with less stringent restrictions, isolated modules make it easier to set clear expectations and guidelines that work across a variety of use cases.
Surprising Edge Cases¶
Note that isolated modules do create some surprising edge cases. Most
notably, each module object will typically not share its classes and
exceptions with other similar modules. Continuing from the
example above,
note that old_binascii.Error
and binascii.Error
are
separate objects. In the following code, the exception is not caught:
>>> old_binascii.Error == binascii.Error
False
>>> try:
... old_binascii.unhexlify(b'qwertyuiop')
... except binascii.Error:
... print('boo')
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
binascii.Error: Non-hexadecimal digit found
This is expected. Notice that pure-Python modules behave the same way: it is a part of how Python works.
The goal is to make extension modules safe at the C level, not to make
hacks behave intuitively. Mutating sys.modules
“manually” counts
as a hack.
Making Modules Safe with Multiple Interpreters¶
Managing Global State¶
Sometimes, the state associated with a Python module is not specific to that module, but to the entire process (or something else “more global” than a module). For example:
The
readline
module manages the terminal.A module running on a circuit board wants to control the on-board LED.
In these cases, the Python module should provide access to the global state, rather than own it. If possible, write the module so that multiple copies of it can access the state independently (along with other libraries, whether for Python or other languages). If that is not possible, consider explicit locking.
If it is necessary to use process-global state, the simplest way to avoid issues with multiple interpreters is to explicitly prevent a module from being loaded more than once per process—see Opt-Out: Limiting to One Module Object per Process.
Managing Per-Module State¶
To use per-module state, use multi-phase extension module initialization. This signals that your module supports multiple interpreters correctly.
Set PyModuleDef.m_size
to a positive number to request that many
bytes of storage local to the module. Usually, this will be set to the
size of some module-specific struct
, which can store all of the
module’s C-level state. In particular, it is where you should put
pointers to classes (including exceptions, but excluding static types)
and settings (e.g. csv
’s field_size_limit
)
which the C code needs to function.
Note
Another option is to store state in the module’s __dict__
,
but you must avoid crashing when users modify __dict__
from
Python code. This usually means error- and type-checking at the C level,
which is easy to get wrong and hard to test sufficiently.
However, if module state is not needed in C code, storing it in
__dict__
only is a good idea.
If the module state includes PyObject
pointers, the module object
must hold references to those objects and implement the module-level hooks
m_traverse
, m_clear
and m_free
. These work like
tp_traverse
, tp_clear
and tp_free
of a class. Adding them will
require some work and make the code longer; this is the price for
modules which can be unloaded cleanly.
An example of a module with per-module state is currently available as xxlimited; example module initialization shown at the bottom of the file.
Opt-Out: Limiting to One Module Object per Process¶
A non-negative PyModuleDef.m_size
signals that a module supports
multiple interpreters correctly. If this is not yet the case for your
module, you can explicitly make your module loadable only once per
process. For example:
// A process-wide flag
static int loaded = 0;
// Mutex to provide thread safety (only needed for free-threaded Python)
static PyMutex modinit_mutex = {0};
static int
exec_module(PyObject* module)
{
PyMutex_Lock(&modinit_mutex);
if (loaded) {
PyMutex_Unlock(&modinit_mutex);
PyErr_SetString(PyExc_ImportError,
"cannot load module more than once per process");
return -1;
}
loaded = 1;
PyMutex_Unlock(&modinit_mutex);
// ... rest of initialization
}
If your module’s PyModuleDef.m_clear
function is able to prepare
for future re-initialization, it should clear the loaded
flag.
In this case, your module won’t support multiple instances existing
concurrently, but it will, for example, support being loaded after
Python runtime shutdown (Py_FinalizeEx()
) and re-initialization
(Py_Initialize()
).
Module State Access from Functions¶
Accessing the state from module-level functions is straightforward.
Functions get the module object as their first argument; for extracting
the state, you can use PyModule_GetState
:
static PyObject *
func(PyObject *module, PyObject *args)
{
my_struct *state = (my_struct*)PyModule_GetState(module);
if (state == NULL) {
return NULL;
}
// ... rest of logic
}
Note
PyModule_GetState
may return NULL
without setting an
exception if there is no module state, i.e. PyModuleDef.m_size
was
zero. In your own module, you’re in control of m_size
, so this is
easy to prevent.
Heap Types¶
Traditionally, types defined in C code are static; that is,
static PyTypeObject
structures defined directly in code and
initialized using PyType_Ready()
.
Such types are necessarily shared across the process. Sharing them
between module objects requires paying attention to any state they own
or access. To limit the possible issues, static types are immutable at
the Python level: for example, you can’t set str.myattribute = 123
.
CPython implementation detail: Sharing truly immutable objects between interpreters is fine, as long as they don’t provide access to mutable objects. However, in CPython, every Python object has a mutable implementation detail: the reference count. Changes to the refcount are guarded by the GIL. Thus, code that shares any Python objects across interpreters implicitly depends on CPython’s current, process-wide GIL.
Because they are immutable and process-global, static types cannot access
“their” module state.
If any method of such a type requires access to module state,
the type must be converted to a heap-allocated type, or heap type
for short. These correspond more closely to classes created by Python’s
class
statement.
For new modules, using heap types by default is a good rule of thumb.
Changing Static Types to Heap Types¶
Static types can be converted to heap types, but note that the heap type API was not designed for “lossless” conversion from static types—that is, creating a type that works exactly like a given static type. So, when rewriting the class definition in a new API, you are likely to unintentionally change a few details (e.g. pickleability or inherited slots). Always test the details that are important to you.
Watch out for the following two points in particular (but note that this is not a comprehensive list):
Unlike static types, heap type objects are mutable by default. Use the
Py_TPFLAGS_IMMUTABLETYPE
flag to prevent mutability.Heap types inherit
tp_new
by default, so it may become possible to instantiate them from Python code. You can prevent this with thePy_TPFLAGS_DISALLOW_INSTANTIATION
flag.
Defining Heap Types¶
Heap types can be created by filling a PyType_Spec
structure, a
description or “blueprint” of a class, and calling
PyType_FromModuleAndSpec()
to construct a new class object.
Note
Other functions, like PyType_FromSpec()
, can also create
heap types, but PyType_FromModuleAndSpec()
associates the module
with the class, allowing access to the module state from methods.
The class should generally be stored in both the module state (for
safe access from C) and the module’s __dict__
(for access from
Python code).
Garbage-Collection Protocol¶
Instances of heap types hold a reference to their type. This ensures that the type isn’t destroyed before all its instances are, but may result in reference cycles that need to be broken by the garbage collector.
To avoid memory leaks, instances of heap types must implement the garbage collection protocol. That is, heap types should:
Have the
Py_TPFLAGS_HAVE_GC
flag.Define a traverse function using
Py_tp_traverse
, which visits the type (e.g. usingPy_VISIT(Py_TYPE(self))
).
Please refer to the documentation of
Py_TPFLAGS_HAVE_GC
and tp_traverse
for additional considerations.
The API for defining heap types grew organically, leaving it somewhat awkward to use in its current state. The following sections will guide you through common issues.
tp_traverse
in Python 3.8 and lower¶
The requirement to visit the type from tp_traverse
was added in Python 3.9.
If you support Python 3.8 and lower, the traverse function must not
visit the type, so it must be more complicated:
static int my_traverse(PyObject *self, visitproc visit, void *arg)
{
if (Py_Version >= 0x03090000) {
Py_VISIT(Py_TYPE(self));
}
return 0;
}
Unfortunately, Py_Version
was only added in Python 3.11.
As a replacement, use:
PY_VERSION_HEX
, if not using the stable ABI, orsys.version_info
(viaPySys_GetObject()
andPyArg_ParseTuple()
).
Delegating tp_traverse
¶
If your traverse function delegates to the tp_traverse
of its base class (or another type), ensure that Py_TYPE(self)
is visited
only once.
Note that only heap type are expected to visit the type in tp_traverse
.
For example, if your traverse function includes:
base->tp_traverse(self, visit, arg)
…and base
may be a static type, then it should also include:
if (base->tp_flags & Py_TPFLAGS_HEAPTYPE) {
// a heap type's tp_traverse already visited Py_TYPE(self)
} else {
if (Py_Version >= 0x03090000) {
Py_VISIT(Py_TYPE(self));
}
}
It is not necessary to handle the type’s reference count in
tp_new
and tp_clear
.
Defining tp_dealloc
¶
If your type has a custom tp_dealloc
function,
it needs to:
call
PyObject_GC_UnTrack()
before any fields are invalidated, anddecrement the reference count of the type.
To keep the type valid while tp_free
is called, the type’s refcount needs
to be decremented after the instance is deallocated. For example:
static void my_dealloc(PyObject *self)
{
PyObject_GC_UnTrack(self);
...
PyTypeObject *type = Py_TYPE(self);
type->tp_free(self);
Py_DECREF(type);
}
The default tp_dealloc
function does this, so
if your type does not override
tp_dealloc
you don’t need to add it.
Not overriding tp_free
¶
The tp_free
slot of a heap type must be set to
PyObject_GC_Del()
.
This is the default; do not override it.
Avoiding PyObject_New
¶
GC-tracked objects need to be allocated using GC-aware functions.
If you use PyObject_New()
or PyObject_NewVar()
:
Get and call type’s
tp_alloc
slot, if possible. That is, replaceTYPE *o = PyObject_New(TYPE, typeobj)
with:TYPE *o = typeobj->tp_alloc(typeobj, 0);
Replace
o = PyObject_NewVar(TYPE, typeobj, size)
with the same, but use size instead of the 0.If the above is not possible (e.g. inside a custom
tp_alloc
), callPyObject_GC_New()
orPyObject_GC_NewVar()
:TYPE *o = PyObject_GC_New(TYPE, typeobj); TYPE *o = PyObject_GC_NewVar(TYPE, typeobj, size);
Module State Access from Classes¶
If you have a type object defined with PyType_FromModuleAndSpec()
,
you can call PyType_GetModule()
to get the associated module, and then
PyModule_GetState()
to get the module’s state.
To save a some tedious error-handling boilerplate code, you can combine
these two steps with PyType_GetModuleState()
, resulting in:
my_struct *state = (my_struct*)PyType_GetModuleState(type);
if (state == NULL) {
return NULL;
}
Module State Access from Regular Methods¶
Accessing the module-level state from methods of a class is somewhat more complicated, but is possible thanks to API introduced in Python 3.9. To get the state, you need to first get the defining class, and then get the module state from it.
The largest roadblock is getting the class a method was defined in, or that method’s “defining class” for short. The defining class can have a reference to the module it is part of.
Do not confuse the defining class with Py_TYPE(self)
. If the method
is called on a subclass of your type, Py_TYPE(self)
will refer to
that subclass, which may be defined in different module than yours.
Note
The following Python code can illustrate the concept.
Base.get_defining_class
returns Base
even
if type(self) == Sub
:
class Base:
def get_type_of_self(self):
return type(self)
def get_defining_class(self):
return __class__
class Sub(Base):
pass
For a method to get its “defining class”, it must use the
METH_METHOD | METH_FASTCALL | METH_KEYWORDS
calling convention
and the corresponding PyCMethod
signature:
PyObject *PyCMethod(
PyObject *self, // object the method was called on
PyTypeObject *defining_class, // defining class
PyObject *const *args, // C array of arguments
Py_ssize_t nargs, // length of "args"
PyObject *kwnames) // NULL, or dict of keyword arguments
Once you have the defining class, call PyType_GetModuleState()
to get
the state of its associated module.
For example:
static PyObject *
example_method(PyObject *self,
PyTypeObject *defining_class,
PyObject *const *args,
Py_ssize_t nargs,
PyObject *kwnames)
{
my_struct *state = (my_struct*)PyType_GetModuleState(defining_class);
if (state == NULL) {
return NULL;
}
... // rest of logic
}
PyDoc_STRVAR(example_method_doc, "...");
static PyMethodDef my_methods[] = {
{"example_method",
(PyCFunction)(void(*)(void))example_method,
METH_METHOD|METH_FASTCALL|METH_KEYWORDS,
example_method_doc}
{NULL},
}
Module State Access from Slot Methods, Getters and Setters¶
Note
This is new in Python 3.11.
Slot methods—the fast C equivalents for special methods, such as
nb_add
for __add__
or
tp_new
for initialization—have a very simple API that
doesn’t allow passing in the defining class, unlike with PyCMethod
.
The same goes for getters and setters defined with
PyGetSetDef
.
To access the module state in these cases, use the
PyType_GetModuleByDef()
function, and pass in the module definition.
Once you have the module, call PyModule_GetState()
to get the state:
PyObject *module = PyType_GetModuleByDef(Py_TYPE(self), &module_def);
my_struct *state = (my_struct*)PyModule_GetState(module);
if (state == NULL) {
return NULL;
}
PyType_GetModuleByDef()
works by searching the
method resolution order (i.e. all superclasses) for the first
superclass that has a corresponding module.
Note
In very exotic cases (inheritance chains spanning multiple modules
created from the same definition), PyType_GetModuleByDef()
might not
return the module of the true defining class. However, it will always
return a module with the same definition, ensuring a compatible
C memory layout.
Lifetime of the Module State¶
When a module object is garbage-collected, its module state is freed. For each pointer to (a part of) the module state, you must hold a reference to the module object.
Usually this is not an issue, because types created with
PyType_FromModuleAndSpec()
, and their instances, hold a reference
to the module.
However, you must be careful in reference counting when you reference
module state from other places, such as callbacks for external
libraries.
Open Issues¶
Several issues around per-module state and heap types are still open.
Discussions about improving the situation are best held on the discuss forum under c-api tag.
Per-Class Scope¶
It is currently (as of Python 3.11) not possible to attach state to individual types without relying on CPython implementation details (which may change in the future—perhaps, ironically, to allow a proper solution for per-class scope).
Lossless Conversion to Heap Types¶
The heap type API was not designed for “lossless” conversion from static types; that is, creating a type that works exactly like a given static type.


— Mailcap file handling

mailcap
— Mailcap file handling¶
Deprecated since version 3.11, removed in version 3.13.
This module is no longer part of the Python standard library. It was removed in Python 3.13 after being deprecated in Python 3.11. The removal was decided in PEP 594.
The last version of Python that provided the mailcap
module was
Python 3.12.


Using the Python Interpreter

2. Using the Python Interpreter¶
2.1. Invoking the Interpreter¶
The Python interpreter is usually installed as /usr/local/bin/python3.14
on those machines where it is available; putting /usr/local/bin
in your
Unix shell’s search path makes it possible to start it by typing the command:
python3.14
to the shell. [1] Since the choice of the directory where the interpreter lives
is an installation option, other places are possible; check with your local
Python guru or system administrator. (E.g., /usr/local/python
is a
popular alternative location.)
On Windows machines where you have installed Python from the Microsoft Store, the python3.14
command will be available. If you have
the py.exe launcher installed, you can use the py
command. See Python install manager for other ways to launch Python.
Typing an end-of-file character (Control-D on Unix, Control-Z on
Windows) at the primary prompt causes the interpreter to exit with a zero exit
status. If that doesn’t work, you can exit the interpreter by typing the
following command: quit()
.
The interpreter’s line-editing features include interactive editing, history
substitution and code completion on most systems.
Perhaps the quickest check to see whether command line editing is supported is
typing a word in on the Python prompt, then pressing Left arrow (or Control-b).
If the cursor moves, you have command line editing; see Appendix
Interactive Input Editing and History Substitution for an introduction to the keys.
If nothing appears to happen, or if a sequence like ^[[D
or ^B
appears,
command line editing isn’t available; you’ll only be able to use
backspace to remove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.
A second way of starting the interpreter is python -c command [arg] ...
,
which executes the statement(s) in command, analogous to the shell’s
-c
option. Since Python statements often contain spaces or other
characters that are special to the shell, it is usually advised to quote
command in its entirety.
Some Python modules are also useful as scripts. These can be invoked using
python -m module [arg] ...
, which executes the source file for module as
if you had spelled out its full name on the command line.
When a script file is used, it is sometimes useful to be able to run the script
and enter interactive mode afterwards. This can be done by passing -i
before the script.
All command line options are described in Command line and environment.
2.1.1. Argument Passing¶
When known to the interpreter, the script name and additional arguments
thereafter are turned into a list of strings and assigned to the argv
variable in the sys
module. You can access this list by executing import
sys
. The length of the list is at least one; when no script and no arguments
are given, sys.argv[0]
is an empty string. When the script name is given as
'-'
(meaning standard input), sys.argv[0]
is set to '-'
. When
-c
command is used, sys.argv[0]
is set to '-c'
. When
-m
module is used, sys.argv[0]
is set to the full name of the
located module. Options found after -c
command or -m
module are not consumed by the Python interpreter’s option processing but
left in sys.argv
for the command or module to handle.
2.1.2. Interactive Mode¶
When commands are read from a tty, the interpreter is said to be in interactive
mode. In this mode it prompts for the next command with the primary prompt,
usually three greater-than signs (>>>
); for continuation lines it prompts
with the secondary prompt, by default three dots (...
). The interpreter
prints a welcome message stating its version number and a copyright notice
before printing the first prompt:
$ python3.14
Python 3.14 (default, April 4 2024, 09:25:04)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
Continuation lines are needed when entering a multi-line construct. As an
example, take a look at this if
statement:
>>> the_world_is_flat = True
>>> if the_world_is_flat:
... print("Be careful not to fall off!")
...
Be careful not to fall off!
For more on interactive mode, see Interactive Mode.
2.2. The Interpreter and Its Environment¶
2.2.1. Source Code Encoding¶
By default, Python source files are treated as encoded in UTF-8. In that encoding, characters of most languages in the world can be used simultaneously in string literals, identifiers and comments — although the standard library only uses ASCII characters for identifiers, a convention that any portable code should follow. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.
To declare an encoding other than the default one, a special comment line should be added as the first line of the file. The syntax is as follows:
# -*- coding: encoding -*-
where encoding is one of the valid codecs
supported by Python.
For example, to declare that Windows-1252 encoding is to be used, the first line of your source code file should be:
# -*- coding: cp1252 -*-
One exception to the first line rule is when the source code starts with a UNIX “shebang” line. In this case, the encoding declaration should be added as the second line of the file. For example:
#!/usr/bin/env python3
# -*- coding: cp1252 -*-
Footnotes


Security Considerations

Security Considerations¶
The following modules have specific security considerations:
hashlib
: all constructors take a “usedforsecurity” keyword-only argument disabling known insecure and blocked algorithmshttp.server
is not suitable for production use, only implementing basic security checks. See the security considerations.random
shouldn’t be used for security purposes, usesecrets
insteadshelve
: shelve is based on pickle and thus unsuitable for dealing with untrusted sourcestempfile
: mktemp is deprecated due to vulnerability to race conditionszipfile
: maliciously prepared .zip files can cause disk volume exhaustion
The -I
command line option can be used to run Python in isolated
mode. When it cannot be used, the -P
option or the
PYTHONSAFEPATH
environment variable can be used to not prepend a
potentially unsafe path to sys.path
such as the current directory, the
script’s directory or an empty string.


Library and Extension FAQ¶
General Library Questions¶
How do I find a module or application to perform task X?¶
Check the Library Reference to see if there’s a relevant standard library module. (Eventually you’ll learn what’s in the standard library and will be able to skip this step.)
For third-party packages, search the Python Package Index or try Google or another web search engine. Searching for “Python” plus a keyword or two for your topic of interest will usually find something helpful.
Where is the math.py (socket.py, regex.py, etc.) source file?¶
If you can’t find a source file for a module it may be a built-in or
dynamically loaded module implemented in C, C++ or other compiled language.
In this case you may not have the source file or it may be something like
mathmodule.c
, somewhere in a C source directory (not on the Python Path).
There are (at least) three kinds of modules in Python:
modules written in Python (.py);
modules written in C and dynamically loaded (.dll, .pyd, .so, .sl, etc);
modules written in C and linked with the interpreter; to get a list of these, type:
import sys print(sys.builtin_module_names)
How do I make a Python script executable on Unix?¶
You need to do two things: the script file’s mode must be executable and the
first line must begin with #!
followed by the path of the Python
interpreter.
The first is done by executing chmod +x scriptfile
or perhaps chmod 755
scriptfile
.
The second can be done in a number of ways. The most straightforward way is to write
#!/usr/local/bin/python
as the very first line of your file, using the pathname for where the Python interpreter is installed on your platform.
If you would like the script to be independent of where the Python interpreter
lives, you can use the env program. Almost all Unix variants support
the following, assuming the Python interpreter is in a directory on the user’s
PATH
:
#!/usr/bin/env python
Don’t do this for CGI scripts. The PATH
variable for CGI scripts is
often very minimal, so you need to use the actual absolute pathname of the
interpreter.
Occasionally, a user’s environment is so full that the /usr/bin/env program fails; or there’s no env program at all. In that case, you can try the following hack (due to Alex Rezinsky):
#! /bin/sh
""":"
exec python $0 ${1+"$@"}
"""
The minor disadvantage is that this defines the script’s __doc__ string. However, you can fix that by adding
__doc__ = """...Whatever..."""
Is there a curses/termcap package for Python?¶
For Unix variants: The standard Python source distribution comes with a curses module in the Modules subdirectory, though it’s not compiled by default. (Note that this is not available in the Windows distribution – there is no curses module for Windows.)
The curses
module supports basic curses features as well as many additional
functions from ncurses and SYSV curses such as colour, alternative character set
support, pads, and mouse support. This means the module isn’t compatible with
operating systems that only have BSD curses, but there don’t seem to be any
currently maintained OSes that fall into this category.
Is there an equivalent to C’s onexit() in Python?¶
The atexit
module provides a register function that is similar to C’s
onexit()
.
Why don’t my signal handlers work?¶
The most common problem is that the signal handler is declared with the wrong argument list. It is called as
handler(signum, frame)
so it should be declared with two parameters:
def handler(signum, frame):
...
Common tasks¶
How do I test a Python program or component?¶
Python comes with two testing frameworks. The doctest
module finds
examples in the docstrings for a module and runs them, comparing the output with
the expected output given in the docstring.
The unittest
module is a fancier testing framework modelled on Java and
Smalltalk testing frameworks.
To make testing easier, you should use good modular design in your program. Your program should have almost all functionality encapsulated in either functions or class methods – and this sometimes has the surprising and delightful effect of making the program run faster (because local variable accesses are faster than global accesses). Furthermore the program should avoid depending on mutating global variables, since this makes testing much more difficult to do.
The “global main logic” of your program may be as simple as
if __name__ == "__main__":
main_logic()
at the bottom of the main module of your program.
Once your program is organized as a tractable collection of function and class behaviours, you should write test functions that exercise the behaviours. A test suite that automates a sequence of tests can be associated with each module. This sounds like a lot of work, but since Python is so terse and flexible it’s surprisingly easy. You can make coding much more pleasant and fun by writing your test functions in parallel with the “production code”, since this makes it easy to find bugs and even design flaws earlier.
“Support modules” that are not intended to be the main module of a program may include a self-test of the module.
if __name__ == "__main__":
self_test()
Even programs that interact with complex external interfaces may be tested when the external interfaces are unavailable by using “fake” interfaces implemented in Python.
How do I create documentation from doc strings?¶
The pydoc
module can create HTML from the doc strings in your Python
source code. An alternative for creating API documentation purely from
docstrings is epydoc. Sphinx can also include docstring content.
How do I get a single keypress at a time?¶
For Unix variants there are several solutions. It’s straightforward to do this using curses, but curses is a fairly large module to learn.
Threads¶
How do I program using threads?¶
Be sure to use the threading
module and not the _thread
module.
The threading
module builds convenient abstractions on top of the
low-level primitives provided by the _thread
module.
None of my threads seem to run: why?¶
As soon as the main thread exits, all threads are killed. Your main thread is running too quickly, giving the threads no time to do any work.
A simple fix is to add a sleep to the end of the program that’s long enough for all the threads to finish:
import threading, time
def thread_task(name, n):
for i in range(n):
print(name, i)
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10) # <---------------------------!
But now (on many platforms) the threads don’t run in parallel, but appear to run sequentially, one at a time! The reason is that the OS thread scheduler doesn’t start a new thread until the previous thread is blocked.
A simple fix is to add a tiny sleep to the start of the run function:
def thread_task(name, n):
time.sleep(0.001) # <--------------------!
for i in range(n):
print(name, i)
for i in range(10):
T = threading.Thread(target=thread_task, args=(str(i), i))
T.start()
time.sleep(10)
Instead of trying to guess a good delay value for time.sleep()
,
it’s better to use some kind of semaphore mechanism. One idea is to use the
queue
module to create a queue object, let each thread append a token to
the queue when it finishes, and let the main thread read as many tokens from the
queue as there are threads.
How do I parcel out work among a bunch of worker threads?¶
The easiest way is to use the concurrent.futures
module,
especially the ThreadPoolExecutor
class.
Or, if you want fine control over the dispatching algorithm, you can write
your own logic manually. Use the queue
module to create a queue
containing a list of jobs. The Queue
class maintains a
list of objects and has a .put(obj)
method that adds items to the queue and
a .get()
method to return them. The class will take care of the locking
necessary to ensure that each job is handed out exactly once.
Here’s a trivial example:
import threading, queue, time
# The worker thread gets jobs off the queue. When the queue is empty, it
# assumes there will be no more work and exits.
# (Realistically workers will run until terminated.)
def worker():
print('Running worker')
time.sleep(0.1)
while True:
try:
arg = q.get(block=False)
except queue.Empty:
print('Worker', threading.current_thread(), end=' ')
print('queue empty')
break
else:
print('Worker', threading.current_thread(), end=' ')
print('running with argument', arg)
time.sleep(0.5)
# Create queue
q = queue.Queue()
# Start a pool of 5 workers
for i in range(5):
t = threading.Thread(target=worker, name='worker %i' % (i+1))
t.start()
# Begin adding work to the queue
for i in range(50):
q.put(i)
# Give threads time to run
print('Main thread sleeping')
time.sleep(5)
When run, this will produce the following output:
Running worker
Running worker
Running worker
Running worker
Running worker
Main thread sleeping
Worker <Thread(worker 1, started 130283832797456)> running with argument 0
Worker <Thread(worker 2, started 130283824404752)> running with argument 1
Worker <Thread(worker 3, started 130283816012048)> running with argument 2
Worker <Thread(worker 4, started 130283807619344)> running with argument 3
Worker <Thread(worker 5, started 130283799226640)> running with argument 4
Worker <Thread(worker 1, started 130283832797456)> running with argument 5
...
Consult the module’s documentation for more details; the Queue
class provides a featureful interface.
What kinds of global value mutation are thread-safe?¶
A global interpreter lock (GIL) is used internally to ensure that only one
thread runs in the Python VM at a time. In general, Python offers to switch
among threads only between bytecode instructions; how frequently it switches can
be set via sys.setswitchinterval()
. Each bytecode instruction and
therefore all the C implementation code reached from each instruction is
therefore atomic from the point of view of a Python program.
In theory, this means an exact accounting requires an exact understanding of the PVM bytecode implementation. In practice, it means that operations on shared variables of built-in data types (ints, lists, dicts, etc) that “look atomic” really are.
For example, the following operations are all atomic (L, L1, L2 are lists, D, D1, D2 are dicts, x, y are objects, i, j are ints):
L.append(x)
L1.extend(L2)
x = L[i]
x = L.pop()
L1[i:j] = L2
L.sort()
x = y
x.field = y
D[x] = y
D1.update(D2)
D.keys()
These aren’t:
i = i+1
L.append(L[-1])
L[i] = L[j]
D[x] = D[x] + 1
Operations that replace other objects may invoke those other objects’
__del__()
method when their reference count reaches zero, and that can
affect things. This is especially true for the mass updates to dictionaries and
lists. When in doubt, use a mutex!
Can’t we get rid of the Global Interpreter Lock?¶
The global interpreter lock (GIL) is often seen as a hindrance to Python’s deployment on high-end multiprocessor server machines, because a multi-threaded Python program effectively only uses one CPU, due to the insistence that (almost) all Python code can only run while the GIL is held.
With the approval of PEP 703 work is now underway to remove the GIL from the CPython implementation of Python. Initially it will be implemented as an optional compiler flag when building the interpreter, and so separate builds will be available with and without the GIL. Long-term, the hope is to settle on a single build, once the performance implications of removing the GIL are fully understood. Python 3.13 is likely to be the first release containing this work, although it may not be completely functional in this release.
The current work to remove the GIL is based on a fork of Python 3.9 with the GIL removed by Sam Gross. Prior to that, in the days of Python 1.5, Greg Stein actually implemented a comprehensive patch set (the “free threading” patches) that removed the GIL and replaced it with fine-grained locking. Adam Olsen did a similar experiment in his python-safethread project. Unfortunately, both of these earlier experiments exhibited a sharp drop in single-thread performance (at least 30% slower), due to the amount of fine-grained locking necessary to compensate for the removal of the GIL. The Python 3.9 fork is the first attempt at removing the GIL with an acceptable performance impact.
The presence of the GIL in current Python releases
doesn’t mean that you can’t make good use of Python on multi-CPU machines!
You just have to be creative with dividing the work up between multiple
processes rather than multiple threads. The
ProcessPoolExecutor
class in the new
concurrent.futures
module provides an easy way of doing so; the
multiprocessing
module provides a lower-level API in case you want
more control over dispatching of tasks.
Judicious use of C extensions will also help; if you use a C extension to
perform a time-consuming task, the extension can release the GIL while the
thread of execution is in the C code and allow other threads to get some work
done. Some standard library modules such as zlib
and hashlib
already do this.
An alternative approach to reducing the impact of the GIL is to make the GIL a per-interpreter-state lock rather than truly global. This was first implemented in Python 3.12 and is available in the C API. A Python interface to it is expected in Python 3.13. The main limitation to it at the moment is likely to be 3rd party extension modules, since these must be written with multiple interpreters in mind in order to be usable, so many older extension modules will not be usable.
Input and Output¶
How do I delete a file? (And other file questions…)¶
Use os.remove(filename)
or os.unlink(filename)
; for documentation, see
the os
module. The two functions are identical; unlink()
is simply
the name of the Unix system call for this function.
To remove a directory, use os.rmdir()
; use os.mkdir()
to create one.
os.makedirs(path)
will create any intermediate directories in path
that
don’t exist. os.removedirs(path)
will remove intermediate directories as
long as they’re empty; if you want to delete an entire directory tree and its
contents, use shutil.rmtree()
.
To rename a file, use os.rename(old_path, new_path)
.
To truncate a file, open it using f = open(filename, "rb+")
, and use
f.truncate(offset)
; offset defaults to the current seek position. There’s
also os.ftruncate(fd, offset)
for files opened with os.open()
, where
fd is the file descriptor (a small integer).
The shutil
module also contains a number of functions to work on files
including copyfile()
, copytree()
, and
rmtree()
.
How do I copy a file?¶
The shutil
module contains a copyfile()
function.
Note that on Windows NTFS volumes, it does not copy
alternate data streams
nor resource forks
on macOS HFS+ volumes, though both are now rarely used.
It also doesn’t copy file permissions and metadata, though using
shutil.copy2()
instead will preserve most (though not all) of it.
How do I read (or write) binary data?¶
To read or write complex binary data formats, it’s best to use the struct
module. It allows you to take a string containing binary data (usually numbers)
and convert it to Python objects; and vice versa.
For example, the following code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:
import struct
with open(filename, "rb") as f:
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)
The ‘>’ in the format string forces big-endian data; the letter ‘h’ reads one “short integer” (2 bytes), and ‘l’ reads one “long integer” (4 bytes) from the string.
For data that is more regular (e.g. a homogeneous list of ints or floats),
you can also use the array
module.
I can’t seem to use os.read() on a pipe created with os.popen(); why?¶
os.read()
is a low-level function which takes a file descriptor, a small
integer representing the opened file. os.popen()
creates a high-level
file object, the same type returned by the built-in open()
function.
Thus, to read n bytes from a pipe p created with os.popen()
, you need to
use p.read(n)
.
How do I access the serial (RS232) port?¶
For Win32, OSX, Linux, BSD, Jython, IronPython:
For Unix, see a Usenet post by Mitch Chapman:
Why doesn’t closing sys.stdout (stdin, stderr) really close it?¶
Python file objects are a high-level layer of abstraction on low-level C file descriptors.
For most file objects you create in Python via the built-in open()
function, f.close()
marks the Python file object as being closed from
Python’s point of view, and also arranges to close the underlying C file
descriptor. This also happens automatically in f
’s destructor, when
f
becomes garbage.
But stdin, stdout and stderr are treated specially by Python, because of the
special status also given to them by C. Running sys.stdout.close()
marks
the Python-level file object as being closed, but does not close the
associated C file descriptor.
To close the underlying C file descriptor for one of these three, you should
first be sure that’s what you really want to do (e.g., you may confuse
extension modules trying to do I/O). If it is, use os.close()
:
os.close(stdin.fileno())
os.close(stdout.fileno())
os.close(stderr.fileno())
Or you can use the numeric constants 0, 1 and 2, respectively.
Network/Internet Programming¶
What WWW tools are there for Python?¶
See the chapters titled Internet Protocols and Support and Internet Data Handling in the Library Reference Manual. Python has many modules that will help you build server-side and client-side web systems.
A summary of available frameworks is maintained by Paul Boddie at https://wiki.python.org/moin/WebProgramming.
What module should I use to help with generating HTML?¶
You can find a collection of useful links on the Web Programming wiki page.
How do I send mail from a Python script?¶
Use the standard library module smtplib
.
Here’s a very simple interactive mail sender that uses it. This method will work on any host that supports an SMTP listener.
import sys, smtplib
fromaddr = input("From: ")
toaddrs = input("To: ").split(',')
print("Enter message, end with ^D:")
msg = ''
while True:
line = sys.stdin.readline()
if not line:
break
msg += line
# The actual mail send
server = smtplib.SMTP('localhost')
server.sendmail(fromaddr, toaddrs, msg)
server.quit()
A Unix-only alternative uses sendmail. The location of the sendmail program
varies between systems; sometimes it is /usr/lib/sendmail
, sometimes
/usr/sbin/sendmail
. The sendmail manual page will help you out. Here’s
some sample code:
import os
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
p = os.popen("%s -t -i" % SENDMAIL, "w")
p.write("To: receiver@example.com\n")
p.write("Subject: test\n")
p.write("\n") # blank line separating headers from body
p.write("Some text\n")
p.write("some more text\n")
sts = p.close()
if sts != 0:
print("Sendmail exit status", sts)
How do I avoid blocking in the connect() method of a socket?¶
The select
module is commonly used to help with asynchronous I/O on
sockets.
To prevent the TCP connect from blocking, you can set the socket to non-blocking
mode. Then when you do the connect()
,
you will either connect immediately
(unlikely) or get an exception that contains the error number as .errno
.
errno.EINPROGRESS
indicates that the connection is in progress, but hasn’t
finished yet. Different OSes will return different values, so you’re going to
have to check what’s returned on your system.
You can use the connect_ex()
method
to avoid creating an exception.
It will just return the errno value.
To poll, you can call connect_ex()
again later
– 0
or errno.EISCONN
indicate that you’re connected – or you can pass this
socket to select.select()
to check if it’s writable.
Databases¶
Are there any interfaces to database packages in Python?¶
Yes.
Interfaces to disk-based hashes such as DBM
and GDBM
are also included with standard Python. There is also the
sqlite3
module, which provides a lightweight disk-based relational
database.
Support for most relational databases is available. See the DatabaseProgramming wiki page for details.
How do you implement persistent objects in Python?¶
The pickle
library module solves this in a very general way (though you
still can’t store things like open files, sockets or windows), and the
shelve
library module uses pickle and (g)dbm to create persistent
mappings containing arbitrary Python objects.
Mathematics and Numerics¶
How do I generate random numbers in Python?¶
The standard module random
implements a random number generator. Usage
is simple:
import random
random.random()
This returns a random floating-point number in the range [0, 1).
There are also many other specialized generators in this module, such as:
randrange(a, b)
chooses an integer in the range [a, b).uniform(a, b)
chooses a floating-point number in the range [a, b).normalvariate(mean, sdev)
samples the normal (Gaussian) distribution.
Some higher-level functions operate on sequences directly, such as:
choice(S)
chooses a random element from a given sequence.shuffle(L)
shuffles a list in-place, i.e. permutes it randomly.
There’s also a Random
class you can instantiate to create independent
multiple random number generators.


Socket Programming HOWTO

Socket Programming HOWTO¶
- Author:
Gordon McMillan
Sockets¶
I’m only going to talk about INET (i.e. IPv4) sockets, but they account for at least 99% of the sockets in use. And I’ll only talk about STREAM (i.e. TCP) sockets - unless you really know what you’re doing (in which case this HOWTO isn’t for you!), you’ll get better behavior and performance from a STREAM socket than anything else. I will try to clear up the mystery of what a socket is, as well as some hints on how to work with blocking and non-blocking sockets. But I’ll start by talking about blocking sockets. You’ll need to know how they work before dealing with non-blocking sockets.
Part of the trouble with understanding these things is that “socket” can mean a number of subtly different things, depending on context. So first, let’s make a distinction between a “client” socket - an endpoint of a conversation, and a “server” socket, which is more like a switchboard operator. The client application (your browser, for example) uses “client” sockets exclusively; the web server it’s talking to uses both “server” sockets and “client” sockets.
History¶
Of the various forms of IPC, sockets are by far the most popular. On any given platform, there are likely to be other forms of IPC that are faster, but for cross-platform communication, sockets are about the only game in town.
They were invented in Berkeley as part of the BSD flavor of Unix. They spread like wildfire with the internet. With good reason — the combination of sockets with INET makes talking to arbitrary machines around the world unbelievably easy (at least compared to other schemes).
Creating a Socket¶
Roughly speaking, when you clicked on the link that brought you to this page, your browser did something like the following:
# create an INET, STREAMing socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# now connect to the web server on port 80 - the normal http port
s.connect(("www.python.org", 80))
When the connect
completes, the socket s
can be used to send
in a request for the text of the page. The same socket will read the
reply, and then be destroyed. That’s right, destroyed. Client sockets
are normally only used for one exchange (or a small set of sequential
exchanges).
What happens in the web server is a bit more complex. First, the web server creates a “server socket”:
# create an INET, STREAMing socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
serversocket.bind((socket.gethostname(), 80))
# become a server socket
serversocket.listen(5)
A couple things to notice: we used socket.gethostname()
so that the socket
would be visible to the outside world. If we had used s.bind(('localhost',
80))
or s.bind(('127.0.0.1', 80))
we would still have a “server” socket,
but one that was only visible within the same machine. s.bind(('', 80))
specifies that the socket is reachable by any address the machine happens to
have.
A second thing to note: low number ports are usually reserved for “well known” services (HTTP, SNMP etc). If you’re playing around, use a nice high number (4 digits).
Finally, the argument to listen
tells the socket library that we want it to
queue up as many as 5 connect requests (the normal max) before refusing outside
connections. If the rest of the code is written properly, that should be plenty.
Now that we have a “server” socket, listening on port 80, we can enter the mainloop of the web server:
while True:
# accept connections from outside
(clientsocket, address) = serversocket.accept()
# now do something with the clientsocket
# in this case, we'll pretend this is a threaded server
ct = make_client_thread(clientsocket)
ct.start()
There’s actually 3 general ways in which this loop could work - dispatching a
thread to handle clientsocket
, create a new process to handle
clientsocket
, or restructure this app to use non-blocking sockets, and
multiplex between our “server” socket and any active clientsocket
s using
select
. More about that later. The important thing to understand now is
this: this is all a “server” socket does. It doesn’t send any data. It doesn’t
receive any data. It just produces “client” sockets. Each clientsocket
is
created in response to some other “client” socket doing a connect()
to the
host and port we’re bound to. As soon as we’ve created that clientsocket
, we
go back to listening for more connections. The two “clients” are free to chat it
up - they are using some dynamically allocated port which will be recycled when
the conversation ends.
IPC¶
If you need fast IPC between two processes on one machine, you should look into
pipes or shared memory. If you do decide to use AF_INET sockets, bind the
“server” socket to 'localhost'
. On most platforms, this will take a
shortcut around a couple of layers of network code and be quite a bit faster.
See also
The multiprocessing
integrates cross-platform IPC into a higher-level
API.
Using a Socket¶
The first thing to note, is that the web browser’s “client” socket and the web
server’s “client” socket are identical beasts. That is, this is a “peer to peer”
conversation. Or to put it another way, as the designer, you will have to
decide what the rules of etiquette are for a conversation. Normally, the
connect
ing socket starts the conversation, by sending in a request, or
perhaps a signon. But that’s a design decision - it’s not a rule of sockets.
Now there are two sets of verbs to use for communication. You can use send
and recv
, or you can transform your client socket into a file-like beast and
use read
and write
. The latter is the way Java presents its sockets.
I’m not going to talk about it here, except to warn you that you need to use
flush
on sockets. These are buffered “files”, and a common mistake is to
write
something, and then read
for a reply. Without a flush
in
there, you may wait forever for the reply, because the request may still be in
your output buffer.
Now we come to the major stumbling block of sockets - send
and recv
operate
on the network buffers. They do not necessarily handle all the bytes you hand
them (or expect from them), because their major focus is handling the network
buffers. In general, they return when the associated network buffers have been
filled (send
) or emptied (recv
). They then tell you how many bytes they
handled. It is your responsibility to call them again until your message has
been completely dealt with.
When a recv
returns 0 bytes, it means the other side has closed (or is in
the process of closing) the connection. You will not receive any more data on
this connection. Ever. You may be able to send data successfully; I’ll talk
more about this later.
A protocol like HTTP uses a socket for only one transfer. The client sends a request, then reads a reply. That’s it. The socket is discarded. This means that a client can detect the end of the reply by receiving 0 bytes.
But if you plan to reuse your socket for further transfers, you need to realize
that there is no EOT on a socket. I repeat: if a socket
send
or recv
returns after handling 0 bytes, the connection has been
broken. If the connection has not been broken, you may wait on a recv
forever, because the socket will not tell you that there’s nothing more to
read (for now). Now if you think about that a bit, you’ll come to realize a
fundamental truth of sockets: messages must either be fixed length (yuck), or
be delimited (shrug), or indicate how long they are (much better), or end by
shutting down the connection. The choice is entirely yours, (but some ways are
righter than others).
Assuming you don’t want to end the connection, the simplest solution is a fixed length message:
class MySocket:
"""demonstration class only
- coded for clarity, not efficiency
"""
def __init__(self, sock=None):
if sock is None:
self.sock = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
else:
self.sock = sock
def connect(self, host, port):
self.sock.connect((host, port))
def mysend(self, msg):
totalsent = 0
while totalsent < MSGLEN:
sent = self.sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError("socket connection broken")
totalsent = totalsent + sent
def myreceive(self):
chunks = []
bytes_recd = 0
while bytes_recd < MSGLEN:
chunk = self.sock.recv(min(MSGLEN - bytes_recd, 2048))
if chunk == b'':
raise RuntimeError("socket connection broken")
chunks.append(chunk)
bytes_recd = bytes_recd + len(chunk)
return b''.join(chunks)
The sending code here is usable for almost any messaging scheme - in Python you
send strings, and you can use len()
to determine its length (even if it has
embedded \0
characters). It’s mostly the receiving code that gets more
complex. (And in C, it’s not much worse, except you can’t use strlen
if the
message has embedded \0
s.)
The easiest enhancement is to make the first character of the message an
indicator of message type, and have the type determine the length. Now you have
two recv
s - the first to get (at least) that first character so you can
look up the length, and the second in a loop to get the rest. If you decide to
go the delimited route, you’ll be receiving in some arbitrary chunk size, (4096
or 8192 is frequently a good match for network buffer sizes), and scanning what
you’ve received for a delimiter.
One complication to be aware of: if your conversational protocol allows multiple
messages to be sent back to back (without some kind of reply), and you pass
recv
an arbitrary chunk size, you may end up reading the start of a
following message. You’ll need to put that aside and hold onto it, until it’s
needed.
Prefixing the message with its length (say, as 5 numeric characters) gets more
complex, because (believe it or not), you may not get all 5 characters in one
recv
. In playing around, you’ll get away with it; but in high network loads,
your code will very quickly break unless you use two recv
loops - the first
to determine the length, the second to get the data part of the message. Nasty.
This is also when you’ll discover that send
does not always manage to get
rid of everything in one pass. And despite having read this, you will eventually
get bit by it!
In the interests of space, building your character, (and preserving my competitive position), these enhancements are left as an exercise for the reader. Lets move on to cleaning up.
Binary Data¶
It is perfectly possible to send binary data over a socket. The major problem is
that not all machines use the same formats for binary data. For example,
network byte order
is big-endian, with the most significant byte first,
so a 16 bit integer with the value 1
would be the two hex bytes 00 01
.
However, most common processors (x86/AMD64, ARM, RISC-V), are little-endian,
with the least significant byte first - that same 1
would be 01 00
.
Socket libraries have calls for converting 16 and 32 bit integers - ntohl,
htonl, ntohs, htons
where “n” means network and “h” means host, “s” means
short and “l” means long. Where network order is host order, these do
nothing, but where the machine is byte-reversed, these swap the bytes around
appropriately.
In these days of 64-bit machines, the ASCII representation of binary data is
frequently smaller than the binary representation. That’s because a surprising
amount of the time, most integers have the value 0, or maybe 1.
The string "0"
would be two bytes, while a full 64-bit integer would be 8.
Of course, this doesn’t fit well with fixed-length messages.
Decisions, decisions.
Disconnecting¶
Strictly speaking, you’re supposed to use shutdown
on a socket before you
close
it. The shutdown
is an advisory to the socket at the other end.
Depending on the argument you pass it, it can mean “I’m not going to send
anymore, but I’ll still listen”, or “I’m not listening, good riddance!”. Most
socket libraries, however, are so used to programmers neglecting to use this
piece of etiquette that normally a close
is the same as shutdown();
close()
. So in most situations, an explicit shutdown
is not needed.
One way to use shutdown
effectively is in an HTTP-like exchange. The client
sends a request and then does a shutdown(1)
. This tells the server “This
client is done sending, but can still receive.” The server can detect “EOF” by
a receive of 0 bytes. It can assume it has the complete request. The server
sends a reply. If the send
completes successfully then, indeed, the client
was still receiving.
Python takes the automatic shutdown a step further, and says that when a socket
is garbage collected, it will automatically do a close
if it’s needed. But
relying on this is a very bad habit. If your socket just disappears without
doing a close
, the socket at the other end may hang indefinitely, thinking
you’re just being slow. Please close
your sockets when you’re done.
When Sockets Die¶
Probably the worst thing about using blocking sockets is what happens when the
other side comes down hard (without doing a close
). Your socket is likely to
hang. TCP is a reliable protocol, and it will wait a long, long time
before giving up on a connection. If you’re using threads, the entire thread is
essentially dead. There’s not much you can do about it. As long as you aren’t
doing something dumb, like holding a lock while doing a blocking read, the
thread isn’t really consuming much in the way of resources. Do not try to kill
the thread - part of the reason that threads are more efficient than processes
is that they avoid the overhead associated with the automatic recycling of
resources. In other words, if you do manage to kill the thread, your whole
process is likely to be screwed up.
Non-blocking Sockets¶
If you’ve understood the preceding, you already know most of what you need to know about the mechanics of using sockets. You’ll still use the same calls, in much the same ways. It’s just that, if you do it right, your app will be almost inside-out.
In Python, you use socket.setblocking(False)
to make it non-blocking. In C, it’s
more complex, (for one thing, you’ll need to choose between the BSD flavor
O_NONBLOCK
and the almost indistinguishable POSIX flavor O_NDELAY
, which
is completely different from TCP_NODELAY
), but it’s the exact same idea. You
do this after creating the socket, but before using it. (Actually, if you’re
nuts, you can switch back and forth.)
The major mechanical difference is that send
, recv
, connect
and
accept
can return without having done anything. You have (of course) a
number of choices. You can check return code and error codes and generally drive
yourself crazy. If you don’t believe me, try it sometime. Your app will grow
large, buggy and suck CPU. So let’s skip the brain-dead solutions and do it
right.
Use select
.
In C, coding select
is fairly complex. In Python, it’s a piece of cake, but
it’s close enough to the C version that if you understand select
in Python,
you’ll have little trouble with it in C:
ready_to_read, ready_to_write, in_error = \
select.select(
potential_readers,
potential_writers,
potential_errs,
timeout)
You pass select
three lists: the first contains all sockets that you might
want to try reading; the second all the sockets you might want to try writing
to, and the last (normally left empty) those that you want to check for errors.
You should note that a socket can go into more than one list. The select
call is blocking, but you can give it a timeout. This is generally a sensible
thing to do - give it a nice long timeout (say a minute) unless you have good
reason to do otherwise.
In return, you will get three lists. They contain the sockets that are actually readable, writable and in error. Each of these lists is a subset (possibly empty) of the corresponding list you passed in.
If a socket is in the output readable list, you can be
as-close-to-certain-as-we-ever-get-in-this-business that a recv
on that
socket will return something. Same idea for the writable list. You’ll be able
to send something. Maybe not all you want to, but something is better than
nothing. (Actually, any reasonably healthy socket will return as writable - it
just means outbound network buffer space is available.)
If you have a “server” socket, put it in the potential_readers list. If it comes
out in the readable list, your accept
will (almost certainly) work. If you
have created a new socket to connect
to someone else, put it in the
potential_writers list. If it shows up in the writable list, you have a decent
chance that it has connected.
Actually, select
can be handy even with blocking sockets. It’s one way of
determining whether you will block - the socket returns as readable when there’s
something in the buffers. However, this still doesn’t help with the problem of
determining whether the other end is done, or just busy with something else.
Portability alert: On Unix, select
works both with the sockets and
files. Don’t try this on Windows. On Windows, select
works with sockets
only. Also note that in C, many of the more advanced socket options are done
differently on Windows. In fact, on Windows I usually use threads (which work
very, very well) with my sockets.