Basic utilities (The gevent top level package)

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__:

>>> class MyNoopGreenlet(Greenlet):
...
...     def __init__(self, seconds):
...         Greenlet.__init__(self)
...         self.seconds = seconds
...
...     def _run(self):
...         gevent.sleep(self.seconds)

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
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=False, timeout=None)

Raise the exception in the greenlet.

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

Return None.

Link greenlet’s completion to callable or another greenlet.

If receiver is a callable then it will be called with this instance as an argument once this greenlet’s dead. A callable is called in its own greenlet.

If receiver is a greenlet then an LinkedExited exception will be raised in it once this greenlet’s dead.

If receiver is None, link to the current greenlet.

Always asynchronous, unless receiver is a current greenlet and the result is ready. If this greenlet is already dead, then notification will performed in this loop iteration as soon as this greenlet switches to the hub.

Like link() but receiver is only notified when the greenlet has completed successfully
Like link() but receiver is only notified when the greenlet dies because of unhandled exception
Remove the receiver 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.

This are the shortcuts for:

g = spawn(function, *args, **kwargs)
g.link() # or g.link_value() or g.link_exception()

As Greenlet.link() without argument links to the current greenlet, a gevent.greenlet.LinkedExited exception will be raised if the newly spawned greenlet exits. It is not meant as a way of inter-greenlet communication but more of a way to assert that a background greenlet is running at least as long as the current greenlet.

See Greenlet.link(), Greenlet.link_value() and Greenlet.link_exception() for details.

Useful general functions

gevent.getcurrent()
gevent.sleep(seconds=0)

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. Calling sleep with seconds of 0 is the canonical way of expressing a cooperative yield.

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=False, timeout=None)
gevent.joinall(greenlets, timeout=None, raise_error=False)
gevent.signal(signalnum, handler, *args, **kwargs)
gevent.fork()
gevent.shutdown()
Cancel our CTRL-C handler and wait for core.dispatch() to return.
gevent.reinit()
Wrapper for event_reinit().

Timeouts

class gevent.Timeout(seconds=None, exception=None)

Raise exception in the current greenlet after timeout seconds:

timeout = Timeout(seconds, exception)
timeout.start()
try:
    ... # execution here is limited by timeout
finally:
    timeout.cancel()

When exception is omitted or None, 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
Return True if the timeout is scheduled to be raised.
start()
Schedule the timeout.
classmethod start_new(timeout=None, exception=None)

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.

Table Of Contents

Previous topic

API reference

Next topic

Synchronization primitives (gevent.event module)

This Page