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.
Holds the value returned by the function if the greenlet has finished successfully. Otherwise None.
Holds the exception instance raised by the function if the greenlet has finished with an error. Otherwise None.
Return true if and only if the greenlet has finished execution.
Return true if and only if the greenlet has finished execution successfully, that is, without raising an error.
Schedule the greenlet to run in this loop iteration
Schedule the greenlet to run in the future loop iteration seconds later
Wait until the greenlet finishes or timeout expires. Return None regardless.
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 error.
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.
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()
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.
Create a new Greenlet object and schedule it to run function(*args, **kwargs). This is an alias for Greenlet.spawn().
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().
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.
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.
Cancel our CTRL-C handler and wait for core.dispatch() to return.
Wrapper for event_reinit().
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
Return True if the timeout is scheduled to be raised.
Schedule the timeout.
Create a started Timeout.
This is a shortcut, the exact action depends on timeout‘s type:
Returns the Timeout instance.
If the timeout is pending, cancel it. Otherwise, do nothing.
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.
Next page: Networking interfaces