The most common functions and classes are available in the gevent top level package.
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.
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.
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 errir.
Changed in version 0.13.0: block is now True by default.
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.
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.
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.
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.
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.
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.
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
Create a started Timeout.
This is a shortcut, the exact action depends on timeout‘s type:
Returns the Timeout instance.
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.