- :meth:`get <Greenlet.get>` -- returns the value returned by greenlet or re-raised the exception that killed it.
It is possible to customize the string printed after the traceback by subclassing :class:`Greenlet` class
and redefining its ``__str__`` method.
To subclass a :class:`Greenlet`, override its :meth:`_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)
def __str__(self):
return 'MyNoopGreenlet(%s)' % self.seconds
Greenlets can be killed asynchronously. Killing will resume the sleeping greenlet, but instead
of continuing execution, a :exc:`GreenletExit` will be raised.
>>> g = MyNoopGreenlet(4)
>>> g.start()
>>> g.kill()
>>> g.dead
True
The :exc:`GreenletExit` exception and its subclasses are handled differently then other exceptions.
Raising :exc:`GreenletExit` is not considered an exceptional situation, so the traceback is not printed.
The :exc:`GreenletExit` is returned by :meth:`get <Greenlet.get>` as if it was returned by the greenlet, not raised.
The :meth:`kill <Greenlet.kill>` method can accept an exception to raise:
>>> g = MyNoopGreenlet.spawn(5) # spawn() creates a Greenlet and starts it
>>> g.kill(Exception("A time to kill"))
Traceback (most recent call last):
...
Exception: A time to kill
MyNoopGreenlet(5) failed with Exception
The :meth:`kill <Greenlet.kill>` can also accept a *timeout* argument specifying the number of seconds to wait for the greenlet to exit.
Note, that :meth:`kill <Greenlet.kill>` cannot guarantee that the target greenlet will not ignore the exception and thus it's a good idea always to pass a timeout to :meth:`kill <Greenlet.kill>`.
Timeouts
--------
Many functions in the gevent API are synchronous, blocking the current greenlet until the operation is done. For example,
:meth:`kill <Greenlet.kill>` waits until the target greenlet is :attr:`dead` before returning [#f1]_. Many of those
functions can be made asynchronous by passing ``block=False`` argument.
Furthermore, many of the synchronous functions accept *timeout* argument, which specifies a limit on how long the function
could block (examples: :meth:`Event.wait`, :meth:`Greenlet.join`, :meth:`Greenlet.kill`, :meth:`AsyncResult.get` and many more).
The :class:`socket <gevent.socket.socket>` and :class:`SSLObject <gevent.ssl.SSLObject>` instances can also have a timeout,
set by :meth:`settimeout <gevent.socket.socket.settimeout>` method.
When these are not enough, the :class:`Timeout` class can be used to add timeouts to arbitrary sections of (yielding) code.
Futher reading
--------------
To limit concurrency, use :class:`Pool` class (see `example: dns_mass_resolve.py`_).
Gevent comes with TCP/SSL/HTTP/WSGI servers. See :doc:`servers`.