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 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()
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().
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.
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
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.
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:
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.
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