gevent.monkey – Make the standard library cooperative


The primary purpose of this module is to carefully patch, in place, portions of the standard library with gevent-friendly functions that behave in the same way as the original (at least as closely as possible).

The primary interface to this is the patch_all() function, which performs all the available patches. It accepts arguments to limit the patching to certain modules, but most programs should use the default values as they receive the most wide-spread testing, and some monkey patches have dependencies on others.

Patching should be done as early as possible in the lifecycle of the program. For example, the main module (the one that tests against __main__ or is otherwise the first imported) should begin with this code, ideally before any other imports:

from gevent import monkey

A corollary of the above is that patching should be done on the main thread and should be done while the program is single-threaded.


Some frameworks, such as gunicorn, handle monkey-patching for you. Check their documentation to be sure.


Sometimes it is helpful to know if objects have been monkey-patched, and in advanced cases even to have access to the original standard library functions. This module provides functions for that purpose.

Use as a module

Sometimes it is useful to run existing python scripts or modules that were not built to be gevent aware under gevent. To do so, this module can be run as the main module, passing the script and its arguments. For details, see the main() function.



Check if a module has been replaced with a cooperative version.

Parameters:mod_name (str) – The name of the standard library module, e.g., 'socket'.
is_object_patched(mod_name, item_name)

Check if an object in a module has been replaced with a cooperative version.

  • mod_name (str) – The name of the standard library module, e.g., 'socket'.
  • item_name (str) – The name of the attribute in the module, e.g., 'create_connection'.
get_original(mod_name, item_name)

Retrieve the original object from a module.

If the object has not been patched, then that object will still be retrieved.

  • mod_name (str) – The name of the standard library module, e.g., 'socket'.
  • item_name – A string or sequence of strings naming the attribute(s) on the module mod_name to return.

The original value if a string was given for item_name or a sequence of original values if a sequence was passed.

patch_sys(stdin=True, stdout=True, stderr=True)

Patch sys.std[in,out,err] to use a cooperative IO via a threadpool.

This is relatively dangerous and can have unintended consequences such as hanging the process or misinterpreting control keys when input() and raw_input() are used. patch_all() does not call this function by default.

This method does nothing on Python 3. The Python 3 interpreter wants to flush the TextIOWrapper objects that make up stderr/stdout at shutdown time, but using a threadpool at that time leads to a hang.


Replace os.fork() with gevent.fork(), and, on POSIX, os.waitpid() with gevent.os.waitpid() (if the environment variable GEVENT_NOWAITPID is not defined). Does nothing if fork is not available.


This method must be used with patch_signal() to have proper SIGCHLD handling and thus correct results from waitpid. patch_all() calls both by default.


For SIGCHLD handling to work correctly, the event loop must run. The easiest way to help ensure this is to use patch_all().


Replace time.sleep() with gevent.sleep().

patch_thread(threading=True, _threading_local=True, Event=True, logging=True, existing_locks=True) → None

Replace the standard thread module to make it greenlet-based.

  • threading (bool) – When True (the default), also patch threading.
  • _threading_local (bool) – When True (the default), also patch _threading_local.local.
  • logging (bool) – When True (the default), also patch locks taken if the logging module has been configured.
  • existing_locks (bool) – When True (the default), and the process is still single threaded, make sure that any threading.RLock (and, under Python 3, importlib._bootstrap._ModuleLock) instances that are currently locked can be properly unlocked.


Monkey-patching thread and using multiprocessing.Queue or concurrent.futures.ProcessPoolExecutor (which uses a Queue) will hang the process.

Changed in version 1.1b1: Add logging and existing_locks params.

Changed in version 1.3a2: Event defaults to True.

patch_socket(dns=True, aggressive=True)

Replace the standard socket object with gevent’s cooperative sockets.

Parameters:dns (bool) – When true (the default), also patch address resolution functions in socket. See Name Resolution (DNS) for details.

Replace DNS functions in socket with cooperative versions.

This is only useful if patch_socket() has been called and is done automatically by that method if requested.

patch_ssl() → None

Replace ssl.SSLSocket object and socket wrapping functions in ssl with cooperative versions.

This is only useful if patch_socket() has been called.


Replace with and select.poll() with (where available).

If aggressive is true (the default), also remove other blocking functions from select and (on Python 3.4 and above) selectors:


Replace, subprocess.check_call(), subprocess.check_output() and subprocess.Popen with cooperative versions.


On Windows under Python 3, the API support may not completely match the standard library.


Make the builtin __import__() function greenlet safe under Python 2.


This does nothing under Python 3 as it is not necessary. Python 3 features improved import locks that are per-module, not global.


Make the signal.signal() function work with a monkey-patched os.


This method must be used with patch_os() to have proper SIGCHLD handling. patch_all() calls both by default.


For proper SIGCHLD handling, you must yield to the event loop. Using patch_all() is the easiest way to ensure this.

See also


patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, httplib=False, subprocess=True, sys=False, aggressive=True, Event=True, builtins=True, signal=True)

Do all of the default monkey patching (calls every other applicable function in this module).

Changed in version 1.1: Issue a warning if this function is called multiple times with different arguments. The second and subsequent calls will only add more patches, they can never remove existing patches by setting an argument to False.

Changed in version 1.1: Issue a warning if this function is called with os=False and signal=True. This will cause SIGCHLD handlers to not be called. This may be an error in the future.

Changed in version 1.3a2: Event defaults to True.


gevent.monkey - monkey patch the standard modules to use gevent.

USAGE: python -m gevent.monkey [MONKEY OPTIONS] script [SCRIPT OPTIONS]

If no OPTIONS present, monkey patches all the modules it can patch. You can exclude a module with –no-module, e.g. –no-thread. You can specify a module to patch with –module, e.g. –socket. In the latter case only the modules specified on the command line will be patched.

MONKEY OPTIONS: –verbose –[no-]socket, –[no-]dns, –[no-]time, –[no-]select, –[no-]thread, –[no-]os, –[no-]ssl, –[no-]subprocess, –[no-]sys, –[no-]builtins, –[no-]signal

Next page: gevent.os – Low-level operating system functions from os