gevent – basic utilities

The most common functions and classes are available in the gevent top level package.

Greenlet objects

Greenlet is a light-weight cooperatively-scheduled execution unit.

To start a new greenlet, pass the target function and its arguments to Greenlet constructor and call start():

>>> g = Greenlet(myfunction, 'arg1', 'arg2', kwarg1=1)
>>> g.start()

or use classmethod spawn() which is a shortcut that does the same:

>>> g = Greenlet.spawn(myfunction, 'arg1', 'arg2', kwarg1=1)

To subclass a Greenlet, override its _run() method and call Greenlet.__init__(self) in __init__(): It also a good idea to override __str__(): if _run() raises an exception, its string representation will be printed after the traceback it generated.

class gevent.Greenlet
Greenlet.value

Holds the value returned by the function if the greenlet has finished successfully. Otherwise None.

Greenlet.exception None

Holds the exception instance raised by the function if the greenlet has finished with an error. Otherwise None.

Greenlet.ready()

Return true if and only if the greenlet has finished execution.

Greenlet.successful()

Return true if and only if the greenlet has finished execution successfully, that is, without raising an error.

Greenlet.start()

Schedule the greenlet to run in this loop iteration

Greenlet.start_later(seconds)

Schedule the greenlet to run in the future loop iteration seconds later

Greenlet.join(timeout=None)

Wait until the greenlet finishes or timeout expires. Return None regardless.

Greenlet.get(block=True, timeout=None)

Return the result the greenlet has returned or re-raise the exception it has raised.

If block is False, raise gevent.Timeout if the greenlet is still alive. If block is True, unschedule the current greenlet until the result is available or the timeout expires. In the latter case, gevent.Timeout is raised.

Greenlet.kill(exception=GreenletExit, block=True, timeout=None)

Raise the exception in the greenlet.

If block is True (the default), wait until the greenlet dies or the optional timeout expires. If block is False, the current greenlet is not unscheduled.

The function always returns None and never raises an error.

Changed in version 0.13.0: block is now True by default.

Link greenlet’s completion to a callable.

The callback will be called with this instance as an argument once this greenlet’s dead. A callable is called in its own greenlet.

Like link() but callback is only notified when the greenlet has completed successfully

Like link() but callback is only notified when the greenlet dies because of unhandled exception

Remove the callback set by link() or rawlink()

Being a greenlet subclass, Greenlet also has switch() and throw() methods. However, these should not be used at the application level. Prefer higher-level safe classes, like Event and Queue, instead.

exception gevent.GreenletExit

A special exception that kills the greenlet silently.

When a greenlet raises GreenletExit or a subclass, the traceback is not printed and the greenlet is considered successful. The exception instance is available under value property as if it was returned by the greenlet, not raised.

Spawn helpers

gevent.spawn(function, *args, **kwargs)

Create a new Greenlet object and schedule it to run function(*args, **kwargs). This is an alias for Greenlet.spawn().

gevent.spawn_later(seconds, function, *args, **kwargs)

Create a new Greenlet object and schedule it to run function(*args, **kwargs) in the future loop iteration seconds later. This is an alias for Greenlet.spawn_later().

gevent.spawn_raw(function, *args, **kwargs)

Create a new greenlet object and schedule it to run function(*args, **kwargs). As this returns a raw greenlet, it does not have all the useful methods that gevent.Greenlet has and should only be used as an optimization.

Useful general functions

gevent.getcurrent()
gevent.sleep(seconds=0, ref=True)

Put the current greenlet to sleep for at least seconds.

seconds may be specified as an integer, or a float if fractional seconds are desired.

If ref is false, the greenlet running sleep() will not prevent gevent.wait() from exiting.

gevent.kill(greenlet, exception=GreenletExit)

Kill greenlet asynchronously. The current greenlet is not unscheduled.

Note, that gevent.Greenlet.kill() method does the same and more. However, MAIN greenlet - the one that exists initially - does not have kill() method so you have to use this function.

gevent.killall(greenlets, exception=GreenletExit, block=True, timeout=None)
gevent.joinall(greenlets, timeout=None, raise_error=False, count=None)
gevent.signal(signalnum, handler, *args, **kwargs)
gevent.fork()
gevent.reinit()

Timeouts

class gevent.Timeout(seconds=None, exception=None, ref=True, priority=-1)

Raise exception in the current greenlet after given time period:

timeout = Timeout(seconds, exception)
timeout.start()
try:
    ...  # exception will be raised here, after *seconds* passed since start() call
finally:
    timeout.cancel()

When exception is omitted or None, the Timeout instance itself is raised:

>>> Timeout(0.1).start()
>>> gevent.sleep(0.2)
Traceback (most recent call last):
 ...
Timeout: 0.1 seconds

For Python 2.5 and newer with statement can be used:

with Timeout(seconds, exception) as timeout:
    pass  # ... code block ...

This is equivalent to try/finally block above with one additional feature: if exception is False, the timeout is still raised, but context manager suppresses it, so the code outside the with-block won’t see it.

This is handy for adding a timeout to the functions that don’t support timeout parameter themselves:

data = None
with Timeout(5, False):
    data = mysock.makefile().readline()
if data is None:
    ...  # 5 seconds passed without reading a line
else:
    ...  # a line was read within 5 seconds

Note that, if readline() above catches and doesn’t re-raise BaseException (for example, with except:), then your timeout is screwed.

When catching timeouts, keep in mind that the one you catch maybe not the one you have set; if you going to silent a timeout, always check that it’s the one you need:

timeout = Timeout(1)
timeout.start()
try:
    ...
except Timeout, t:
    if t is not timeout:
        raise # not my timeout
pending None

Return True if the timeout is scheduled to be raised.

start()

Schedule the timeout.

classmethod start_new(timeout=None, exception=None, ref=True)

Create a started Timeout.

This is a shortcut, the exact action depends on timeout‘s type:

  • If timeout is a Timeout, then call its start() method.
  • Otherwise, create a new Timeout instance, passing (timeout, exception) as arguments, then call its start() method.

Returns the Timeout instance.

cancel()

If the timeout is pending, cancel it. Otherwise, do nothing.

gevent.with_timeout(seconds, function, *args, **kwds)

Wrap a call to function with a timeout; if the called function fails to return before the timeout, cancel it and return a flag value, provided by timeout_value keyword argument.

If timeout expires but timeout_value is not provided, raise Timeout.

Keyword argument timeout_value is not passed to function.

Waiting

gevent.wait(objects=None, timeout=None, count=None)

Wait for objects to become ready or for event loop to finish.

If objects is provided, it should be an iterable containg objects implementing wait protocol (rawlink() and unlink() methods):

If objects is None (the default), wait() blocks until all event loops has nothing to do:

  • all greenlets have finished
  • all servers were stopped
  • all event loop watchers were stopped.

If count is None (the default), wait for all of object to become ready.

If count is a number, wait for count object to become ready. (For example, if count is 1 then the function exits when any object in the list is ready).

If timeout is provided, it specifies the maximum number of seconds wait() will block.

Returns the list of ready objects, in the order in which they were ready.

gevent.iwait(objects, timeout=None)

Yield objects as they are ready, until all are ready or timeout expired.

objects must be iterable yielding instance implementing wait protocol (rawlink() and unlink()).

Next page: Networking interfaces