cherrypy.process package


cherrypy.process.plugins module

Site services for use with a Web Site Process Bus.

class cherrypy.process.plugins.Autoreloader(bus, frequency=1, match='.*')[source]

Bases: cherrypy.process.plugins.Monitor

Monitor which re-executes the process when files change.

This plugin restarts the process (via os.execv()) if any of the files it monitors change (or is deleted). By default, the autoreloader monitors all imported modules; you can add to the set by adding to autoreload.files:


If there are imported files you do not wish to monitor, you can adjust the match attribute, a regular expression. For example, to stop monitoring cherrypy itself:

cherrypy.engine.autoreload.match = r'^(?!cherrypy).+'

Like all Monitor plugins, the autoreload plugin takes a frequency argument. The default is 1 second; that is, the autoreloader will examine files once each second.

files = None

The set of files to poll for modifications.

frequency = 1

The interval in seconds at which to poll for modified files.

match = '.*'

A regular expression by which to match filenames.


Reload the process if registered files have been modified.


Start our own background task thread for


Return a Set of sys.modules filenames to monitor.

class cherrypy.process.plugins.BackgroundTask(interval, function, args=[], kwargs={}, bus=None)[source]

Bases: threading.Thread

A subclass of threading.Thread whose run() method repeats.

Use this class for most repeating tasks. It uses time.sleep() to wait for each interval, which isn’t very responsive; that is, even if you call self.cancel(), you’ll have to wait until the sleep() call finishes before the thread stops. To compensate, it defaults to being daemonic, which means it won’t delay stopping the whole process.

class cherrypy.process.plugins.Daemonizer(bus, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null')[source]

Bases: cherrypy.process.plugins.SimplePlugin

Daemonize the running script.

Use this with a Web Site Process Bus via:


When this component finishes, the process is completely decoupled from the parent environment. Please note that when this component is used, the return code from the parent process will still be 0 if a startup error occurs in the forked children. Errors in the initial daemonizing process still return proper exit codes. Therefore, if you use this plugin to daemonize, don’t use the return code as an accurate indicator of whether the process fully started. In fact, that return code only indicates if the process succesfully finished the first fork.

class cherrypy.process.plugins.DropPrivileges(bus, umask=None, uid=None, gid=None)[source]

Bases: cherrypy.process.plugins.SimplePlugin

Drop privileges. uid/gid arguments not available on Windows.

Special thanks to Gavin Baker


The gid under which to run. Availability: Unix.


The uid under which to run. Availability: Unix.


The default permission mode for newly created files and directories.

Usually expressed in octal format, for example, 0644. Availability: Unix, Windows.

class cherrypy.process.plugins.Monitor(bus, callback, frequency=60, name=None)[source]

Bases: cherrypy.process.plugins.SimplePlugin

WSPBus listener to periodically run a callback in its own thread.

callback = None

The function to call at intervals.

frequency = 60

The time in seconds between callback runs.


Stop the callback’s background task thread and restart it.


Start our callback in its own background thread.


Stop our callback’s background task thread.

thread = None

A BackgroundTask thread.

class cherrypy.process.plugins.PIDFile(bus, pidfile)[source]

Bases: cherrypy.process.plugins.SimplePlugin

Maintain a PID file via a WSPBus.

class cherrypy.process.plugins.PerpetualTimer(*args, **kwargs)[source]

Bases: threading.Timer

A responsive subclass of threading.Timer whose run() method repeats.

Use this timer only when you really need a very interruptible timer; this checks its ‘finished’ condition up to 20 times a second, which can results in pretty high CPU usage

class cherrypy.process.plugins.SignalHandler(bus)[source]

Bases: object

Register bus channels (and listeners) for system signals.

You can modify what signals your application listens for, and what it does when it receives signals, by modifying SignalHandler.handlers, a dict of {signal name: callback} pairs. The default set is:

handlers = {'SIGTERM': self.bus.exit,
            'SIGHUP': self.handle_SIGHUP,
            'SIGUSR1': self.bus.graceful,

The SignalHandler.handle_SIGHUP`() method calls bus.restart() if the process is daemonized, but bus.exit() if the process is attached to a TTY. This is because Unix window managers tend to send SIGHUP to terminal windows when the user closes them.

Feel free to add signals which are not available on every platform. The SignalHandler will ignore errors raised from attempting to register handlers for unknown signals.


Restart if daemonized, else exit.

handlers = {}

A map from signal names (e.g. ‘SIGTERM’) to handlers (e.g. bus.exit).

set_handler(signal, listener=None)[source]

Subscribe a handler for the given signal (number or name).

If the optional ‘listener’ argument is provided, it will be subscribed as a listener for the given signal’s channel.

If the given signal name or number is not available on the current platform, ValueError is raised.

signals = {<Signals.SIGRTMAX: 64>: 'SIGRTMAX', <Signals.SIGHUP: 1>: 'SIGHUP', <Signals.SIGINT: 2>: 'SIGINT', <Signals.SIGQUIT: 3>: 'SIGQUIT', <Signals.SIGILL: 4>: 'SIGILL', <Signals.SIGTRAP: 5>: 'SIGTRAP', <Signals.SIGIOT: 6>: 'SIGABRT', <Signals.SIGBUS: 7>: 'SIGBUS', <Signals.SIGFPE: 8>: 'SIGFPE', <Signals.SIGKILL: 9>: 'SIGKILL', <Signals.SIGUSR1: 10>: 'SIGUSR1', <Signals.SIGSEGV: 11>: 'SIGSEGV', <Signals.SIGUSR2: 12>: 'SIGUSR2', <Signals.SIGPIPE: 13>: 'SIGPIPE', <Signals.SIGALRM: 14>: 'SIGALRM', <Signals.SIGTERM: 15>: 'SIGTERM', <Signals.SIGCLD: 17>: 'SIGCLD', <Signals.SIGCONT: 18>: 'SIGCONT', <Signals.SIGSTOP: 19>: 'SIGSTOP', <Signals.SIGTSTP: 20>: 'SIGTSTP', <Signals.SIGTTIN: 21>: 'SIGTTIN', <Signals.SIGTTOU: 22>: 'SIGTTOU', <Signals.SIGURG: 23>: 'SIGURG', <Signals.SIGXCPU: 24>: 'SIGXCPU', <Signals.SIGXFSZ: 25>: 'SIGXFSZ', <Signals.SIGVTALRM: 26>: 'SIGVTALRM', <Signals.SIGPROF: 27>: 'SIGPROF', <Signals.SIGWINCH: 28>: 'SIGWINCH', <Signals.SIGPOLL: 29>: 'SIGPOLL', <Signals.SIGPWR: 30>: 'SIGPWR', <Signals.SIGSYS: 31>: 'SIGSYS', <Signals.SIGRTMIN: 34>: 'SIGRTMIN'}

A map from signal numbers to names.


Subscribe self.handlers to signals.


Unsubscribe self.handlers from signals.

class cherrypy.process.plugins.SimplePlugin(bus)[source]

Bases: object

Plugin base class which auto-subscribes methods for known channels.

bus = None

A Bus, usually cherrypy.engine.


Register this object as a (multi-channel) listener on the bus.


Unregister this object as a listener on the bus.

class cherrypy.process.plugins.ThreadManager(bus)[source]

Bases: cherrypy.process.plugins.SimplePlugin

Manager for HTTP request threads.

If you have control over thread creation and destruction, publish to the ‘acquire_thread’ and ‘release_thread’ channels (for each thread). This will register/unregister the current thread and publish to ‘start_thread’ and ‘stop_thread’ listeners in the bus as needed.

If threads are created and destroyed by code you do not control (e.g., Apache), then, at the beginning of every HTTP request, publish to ‘acquire_thread’ only. You should not publish to ‘release_thread’ in this case, since you do not know whether the thread will be re-used or not. The bus will call ‘stop_thread’ listeners for you when it stops.


Run ‘start_thread’ listeners for the current thread.

If the current thread has already been seen, any ‘start_thread’ listeners will not be run again.


Release all threads and run all ‘stop_thread’ listeners.


Release the current thread and run ‘stop_thread’ listeners.


Release all threads and run all ‘stop_thread’ listeners.

threads = None

A map of {thread ident: index number} pairs.

cherrypy.process.servers module

Starting in CherryPy 3.1, cherrypy.server is implemented as an Engine Plugin. It’s an instance of cherrypy._cpserver.Server, which is a subclass of cherrypy.process.servers.ServerAdapter. The ServerAdapter class is designed to control other servers, as well.

Multiple servers/ports

If you need to start more than one HTTP server (to serve on multiple ports, or protocols, etc.), you can manually register each one and then start them all with engine.start:

s1 = ServerAdapter(
    MyWSGIServer(host='', port=80)
s2 = ServerAdapter(
    another.HTTPServer(host='', SSL=True)


There are also FlupFCGIServer and FlupSCGIServer classes in cherrypy.process.servers. To start an fcgi server, for example, wrap an instance of it in a ServerAdapter:

addr = ('', 4000)
f = servers.FlupFCGIServer(application=cherrypy.tree, bindAddress=addr)
s = servers.ServerAdapter(cherrypy.engine, httpserver=f, bind_addr=addr)

The cherryd startup script will do the above for you via its -f flag. Note that you need to download and install flup yourself, whether you use cherryd or not.


A very simple setup lets your cherry run with FastCGI. You just need the flup library, plus a running Apache server (with mod_fastcgi) or lighttpd server.

CherryPy code

import cherrypy

class HelloWorld:
    '''Sample request handler class.'''
    def index(self):
        return "Hello world!"

# CherryPy autoreload must be disabled for the flup server to work

Then run /deployguide/cherryd with the ‘-f’ arg:

cherryd -c <myconfig> -d -f -i

At the top level in httpd.conf:

FastCgiIpcDir /tmp
FastCgiServer /path/to/cherry.fcgi -idle-timeout 120 -processes 4

And inside the relevant VirtualHost section:

# FastCGI config
AddHandler fastcgi-script .fcgi
ScriptAliasMatch (.*$) /path/to/cherry.fcgi$1

For Lighttpd you can follow these instructions. Within lighttpd.conf make sure mod_fastcgi is active within server.modules. Then, within your $HTTP["host"] directive, configure your fastcgi script like the following:

$HTTP["url"] =~ "" {
  fastcgi.server = (
    "/" => (
      "script.fcgi" => (
        "bin-path" => "/path/to/your/script.fcgi",
        "socket"          => "/tmp/script.sock",
        "check-local"     => "disable",
        "disable-time"    => 1,
        "min-procs"       => 1,
        "max-procs"       => 1, # adjust as needed
} # end of $HTTP["url"] =~ "^/"

Please see Lighttpd FastCGI Docs for an explanation of the possible configuration options.

class cherrypy.process.servers.FlupCGIServer(*args, **kwargs)[source]

Bases: object

Adapter for a flup.server.cgi.WSGIServer.


Start the CGI server.


Stop the HTTP server.

class cherrypy.process.servers.FlupFCGIServer(*args, **kwargs)[source]

Bases: object

Adapter for a flup.server.fcgi.WSGIServer.


Start the FCGI server.


Stop the HTTP server.

class cherrypy.process.servers.FlupSCGIServer(*args, **kwargs)[source]

Bases: object

Adapter for a flup.server.scgi.WSGIServer.


Start the SCGI server.


Stop the HTTP server.

class cherrypy.process.servers.ServerAdapter(bus, httpserver=None, bind_addr=None)[source]

Bases: object

Adapter for an HTTP server.

If you need to start more than one HTTP server (to serve on multiple ports, or protocols, etc.), you can manually register each one and then start them all with bus.start:

s1 = ServerAdapter(bus, MyWSGIServer(host='', port=80))
s2 = ServerAdapter(bus, another.HTTPServer(host='', SSL=True))

The bind address, or if it’s an ephemeral port and the socket has been bound, return the actual port bound.


A description about where this server is bound.


Restart the HTTP server.


Start the HTTP server.


Stop the HTTP server.


Wait until the HTTP server is ready to receive requests.

class cherrypy.process.servers.Timeouts[source]

Bases: object

free = 1
occupied = 5

cherrypy.process.win32 module

Windows service. Requires pywin32.

class cherrypy.process.win32.ConsoleCtrlHandler(bus)[source]

Bases: cherrypy.process.plugins.SimplePlugin

A WSPBus plugin for handling Win32 console events (like Ctrl-C).


Handle console control events (like Ctrl-C).

class cherrypy.process.win32.Win32Bus[source]

Bases: cherrypy.process.wspbus.Bus

A Web Site Process Bus implementation for Win32.

Instead of time.sleep, this bus blocks using native win32event objects.

wait(state, interval=0.1, channel=None)[source]

Wait for the given state(s), KeyboardInterrupt or SystemExit.

Since this class uses native win32event objects, the interval argument is ignored.

cherrypy.process.win32.signal_child(service, command)[source]

cherrypy.process.wspbus module

An implementation of the Web Site Process Bus.

This module is completely standalone, depending only on the stdlib.

Web Site Process Bus

A Bus object is used to contain and manage site-wide behavior: daemonization, HTTP server start/stop, process reload, signal handling, drop privileges, PID file management, logging for all of these, and many more.

In addition, a Bus object provides a place for each web framework to register code that runs in response to site-wide events (like process start and stop), or which controls or otherwise interacts with the site-wide components mentioned above. For example, a framework which uses file-based templates would add known template filenames to an autoreload component.

Ideally, a Bus object will be flexible enough to be useful in a variety of invocation scenarios:

  1. The deployer starts a site from the command line via a framework-neutral deployment script; applications from multiple frameworks are mixed in a single site. Command-line arguments and configuration files are used to define site-wide components such as the HTTP server, WSGI component graph, autoreload behavior, signal handling, etc.
  2. The deployer starts a site via some other process, such as Apache; applications from multiple frameworks are mixed in a single site. Autoreload and signal handling (from Python at least) are disabled.
  3. The deployer starts a site via a framework-specific mechanism; for example, when running tests, exploring tutorials, or deploying single applications from a single framework. The framework controls which site-wide components are enabled as it sees fit.

The Bus object in this package uses topic-based publish-subscribe messaging to accomplish all this. A few topic channels are built in (‘start’, ‘stop’, ‘exit’, ‘graceful’, ‘log’, and ‘main’). Frameworks and site containers are free to define their own. If a message is sent to a channel that has not been defined or has no listeners, there is no effect.

In general, there should only ever be a single Bus object per process. Frameworks and site containers share a single Bus object by publishing messages and subscribing listeners.

The Bus object works as a finite state machine which models the current state of the process. Bus methods move it from one state to another; those methods then publish to subscribed listeners on the channel for the new state.:

   A   A         |
   |    \___     |
   |        \    |
   |         V   V
class cherrypy.process.wspbus.Bus[source]

Bases: object

Process state-machine and messenger for HTTP site deployment.

All listeners for a given channel are guaranteed to be called even if others at the same channel fail. Each failure is logged, but execution proceeds on to the next listener. The only way to stop all processing from inside a listener is to raise SystemExit and stop the whole server.


Wait for the EXITING state, KeyboardInterrupt or SystemExit.

This function is intended to be called only by the main thread. After waiting for the EXITING state, it also waits for all threads to terminate, and then calls os.execv if self.execv is True. This design allows another thread to call bus.restart, yet have the main thread perform the actual execv call (required on some platforms).

execv = False

Stop all services and prepare to exit the process.


Advise all services to reload.

log(msg='', level=20, traceback=False)[source]

Log the given message. Append the last traceback if requested.

max_cloexec_files = 524288
publish(channel, *args, **kwargs)[source]

Return output of all subscribers for the given channel.


Restart the process (may close connections).

This method does not restart the process from the calling thread; instead, it stops the bus and asks the main thread to call execv.


Start all services.

start_with_callback(func, args=None, kwargs=None)[source]

Start ‘func’ in a new thread T, then start self (and return T).

state = states.STOPPED
states = <cherrypy.process.wspbus._StateEnum object>

Stop all services.

subscribe(channel, callback, priority=None)[source]

Add the given callback at the given channel (if not present).

unsubscribe(channel, callback)[source]

Discard the given callback (if present).

wait(state, interval=0.1, channel=None)[source]

Poll for the given state(s) at intervals; publish to channel.

exception cherrypy.process.wspbus.ChannelFailures(*args, **kwargs)[source]

Bases: Exception

Exception raised when errors occur in a listener during Bus.publish().

delimiter = '\n'

Return a list of seen exception instances.


Append the current exception to self.

Module contents

Site container for an HTTP server.

A Web Site Process Bus object is used to connect applications, servers, and frameworks with site-wide services such as daemonization, process reload, signal handling, drop privileges, PID file management, logging for all of these, and many more.

The ‘plugins’ module defines a few abstract and concrete services for use with the bus. Some use tool-specific channels; see the documentation for each class.