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.

A dictionary that is shared between all the greenlets
in a “spawn tree”, that is, a spawning greenlet and all
its descendent greenlets. All children of the main (root)
greenlet start their own spawn trees. Assign a new dictionary
to this attribute on an instance of this class to create a new
spawn tree (as far as locals are concerned).

A lightweight frame-like object capturing the stack when
this greenlet was created as well as the stack when the spawning
greenlet was created (if applicable). This can be passed to
traceback.print_stack().

This is similar to threading.Thread.ident (and id)
in that as long as this object is alive, no other greenlet in
this hub will have the same id, but it makes a stronger
guarantee that the assigned values will be small and
sequential. Sometime after this object has died, the value
will be available for reuse.

To get ids that are unique across all hubs, combine this with
the hub’s minimal_ident.

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.

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.

Note

Depending on what this greenlet is executing and the state
of the event loop, the exception may or may not be raised
immediately when this greenlet resumes execution. It may
be raised on a subsequent green call, or, if this greenlet
exits before making such a call, it may not be raised at
all. As of 1.1, an example where the exception is raised
later is if this greenlet had called sleep(0); an example where the exception is raised
immediately is if this greenlet had called
sleep(0.1).

Caution

Use care when killing greenlets. If the code executing is not
exception safe (e.g., makes proper use of finally) then an
unexpected exception could result in corrupted state.

Greenlet objects have a boolean value (__nonzero__ or
__bool__) which is true if it’s active: started but not dead yet.

It’s possible to use it like this:

>>> g=gevent.spawn(...)>>> whileg: # do something while g is alive

The Greenlet’s __nonzero__ is an improvement on greenlet’s
__nonzero__. The greenlet’s __nonzero__ returns False if greenlet has not
been switched to yet or is already dead. While the latter is OK, the
former is not good, because a just spawned Greenlet has not been
switched to yet and thus would evaluate to False.

Being a greenlet subclass, Greenlet also has switch() and throw() methods. However, these should
not be used at the application level as they can very easily lead to
greenlets that are forever unscheduled. Prefer higher-level safe
classes, like Event and Queue, instead.

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.

Changed in version 1.1b1: If an argument that’s meant to be a function (the first argument in args, or the run keyword )
is given to this classmethod (and not a classmethod of a subclass),
it is verified to be callable. Previously, the spawned greenlet would have failed
when it started running.

Create a new greenlet.greenlet object and schedule it to
run function(*args,**kwargs).

This returns a raw greenlet which does not have all the useful
methods that gevent.Greenlet has. Typically, applications
should prefer spawn(), but this method may
occasionally be useful as an optimization if there are many
greenlets involved.

Changed in version 1.1a3: Verify that function is callable, raising a TypeError if not. Previously,
the spawned greenlet would have failed the first time it was switched to.

Changed in version 1.1b1: If function is not callable, immediately raise a TypeError
instead of spawning a greenlet that will raise an uncaught TypeError.

Changed in version 1.1rc2: Accept keyword arguments for function as previously (incorrectly)
documented. Note that this may incur an additional expense.

Changed in version 1.3a2: Populate the spawning_greenlet and spawn_tree_locals
attributes of the returned greenlet.

seconds may be specified as an integer, or a float if fractional
seconds are desired.

Tip

In the current implementation, a value of 0 (the default)
means to yield execution to any other runnable greenlets, but
this greenlet may be scheduled again before the event loop
cycles (in an extreme case, a greenlet that repeatedly sleeps
with 0 can prevent greenlets that are ready to do I/O from
being scheduled for some (small) period of time); a value greater than
0, on the other hand, will delay running this greenlet until
the next iteration of the loop.

If ref is False, the greenlet running sleep() will not prevent gevent.wait()
from exiting.

Changed in version 1.3a1: Sleeping with a value of 0 will now be bounded to approximately block the
loop for no longer than gevent.getswitchinterval().

Idle is defined as having no other events of the same or higher
priority pending. That is, as long as sockets, timeouts or even
signals of the same or higher priority are being processed, the loop
is not idle.

Kill greenlet asynchronously. The current greenlet is not unscheduled.

Note

The method Greenlet.kill() method does the same and
more (and the same caveats listed there apply here). However, the MAIN
greenlet - the one that exists initially - does not have a
kill() method, and neither do any created with spawn_raw(),
so you have to use this function.

Caution

Use care when killing greenlets. If they are not prepared for
exceptions, this could result in corrupted state.

Changed in version 1.1a2: If the greenlet has a kill method, calls it. This prevents a
greenlet from being switched to for the first time after it’s been
killed but not yet executed.

Forceably terminate all the greenlets by causing them to raise exception.

Caution

Use care when killing greenlets. If they are not prepared for exceptions,
this could result in corrupted state.

Parameters:

greenlets – A bounded iterable of the non-None greenlets to terminate.
All the items in this iterable must be greenlets that belong to the same thread.

exception – The exception to raise in the greenlets. By default this is
GreenletExit.

block (bool) – If True (the default) then this function only returns when all the
greenlets are dead; the current greenlet is unscheduled during that process.
If greenlets ignore the initial exception raised in them,
then they will be joined (with gevent.joinall()) and allowed to die naturally.
If False, this function returns immediately and greenlets will raise
the exception asynchronously.

timeout (float) – A time in seconds to wait for greenlets to die. If given, it is
only honored when block is True.

Raises:

Timeout – If blocking and a timeout is given that elapses before
all the greenlets are dead.

Changed in version 1.1a2: greenlets can be any iterable of greenlets, like an iterator or a set.
Previously it had to be a list or tuple.

This should be called immediately after os.fork() in the
child process. This is done automatically by
gevent.os.fork() or if the os module has been
monkey-patched. If this function is not called in a forked
process, symptoms may include hanging of functions like
socket.getaddrinfo(), and the hub’s threadpool is unlikely
to work.

Note

Registered fork watchers may or may not run before
this function (and thus gevent.os.fork) return. If they have
not run, they will run “soon”, after an iteration of the event loop.
You can force this by inserting a few small (but non-zero) calls to sleep()
after fork returns. (As of gevent 1.1 and before, fork watchers will
not have run, but this may change in the future.)

Note

This function may be removed in a future major release
if the fork process can be more smoothly managed.

Warning

See remarks in gevent.os.fork() about greenlets
and libev watchers in the child process.

Call the handler with the args and kwargs when the process
receives the signal signalnum.

The handler will be run in a new greenlet when the signal is delivered.

This returns an object with the useful method cancel, which, when called,
will prevent future deliveries of signalnum from calling handler.

Note

This may not operate correctly with SIGCHLD if libev child watchers
are used (as they are by default with gevent.os.fork()).

Changed in version 1.1b4: This is an alias for gevent.hub.signal, included for
backwards compatibility; the new module gevent.signal
is replacing this name. This alias will be removed in a
future release.

Changed in version 1.2a1: The handler is required to be callable at construction time.

timeout=Timeout(seconds,exception)timeout.start()try:...# exception will be raised here, after *seconds* passed since start() callfinally:timeout.close()

Note

If the code that the timeout was protecting finishes
executing before the timeout elapses, be sure to close the
timeout so it is not unexpectedly raised in the future. Even if it
is raised, it is a best practice to close it. This try/finally
construct or a with statement is a recommended pattern. (If
the timeout object will be started again, use cancel instead
of close; this is rare.)

When exception is omitted or None, the Timeout instance
itself is raised:

If the seconds argument is not given or is None (e.g.,
Timeout()), then the timeout will never expire and never raise
exception. This is convenient for creating functions which take
an optional timeout parameter of their own. (Note that this is not
the same thing as a seconds value of 0.)

deffunction(args,timeout=None):"A function with an optional timeout."timer=Timeout(timeout)withtimer:...

Caution

A seconds value less than 0.0 (e.g., -1) is poorly defined. In the future,
support for negative values is likely to do the same thing as a value
of None or 0

A seconds value of 0 requests that the event loop spin and poll for I/O;
it will immediately expire as soon as control returns to the event loop.

Use As A Context Manager

To simplify starting and canceling timeouts, the with
statement can be used:

This is equivalent to the try/finally block above with one
additional feature: if exception is the literal False, the
timeout is still raised, but the 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 a timeout parameter themselves:

data=Nonewithgevent.Timeout(5,False):data=mysock.makefile().readline()ifdataisNone:...# 5 seconds passed without reading a lineelse:...# a line was read within 5 seconds

Caution

If readline() above catches and doesn’t re-raise
BaseException (for example, with a bare except:), then
your timeout will fail to function and control won’t be returned
to you when you expect.

Catching Timeouts

When catching timeouts, keep in mind that the one you catch may
not be the one you have set (a calling function may have set its
own timeout); if you going to silence a timeout, always check that
it’s the instance you need:

Changed in version 1.1b2: If seconds is not given or is None, no longer allocate a
native timer object that will never be started.

Changed in version 1.1: Add warning about negative seconds values.

Changed in version 1.3a1: Timeout objects now have a close()
method that must be called when the timeout will no longer be
used to properly clean up native resources.
The with statement does this automatically.

There is one instance of this object at gevent.config. If you
are going to make changes in code, instead of using the documented
environment variables, you need to make the changes before using
any parts of gevent that might need those settings. For example:

This is an importable value. It can be given as a string naming an importable object, or a list of strings in preference order and the first successfully importable object will be used. (Separate values in the environment variable with commas.) It can also be given as the callable object itself (in code). Shorthand names for default objects are [‘block’, ‘thread’, ‘posix’]

This is an importable value. It can be given as a string naming an importable object, or a list of strings in preference order and the first successfully importable object will be used. (Separate values in the environment variable with commas.) It can also be given as the callable object itself (in code).

This is an importable value. It can be given as a string naming an importable object, or a list of strings in preference order and the first successfully importable object will be used. (Separate values in the environment variable with commas.) It can also be given as the callable object itself (in code). Shorthand names for default objects are [‘libev-cffi’, ‘libuv-cffi’, ‘libuv’, ‘libev-cext’]

This is an importable value. It can be given as a string naming an importable object, or a list of strings in preference order and the first successfully importable object will be used. (Separate values in the environment variable with commas.) It can also be given as the callable object itself (in code). Shorthand names for default objects are [‘dnspython’, ‘block’, ‘ares’, ‘thread’]

A list of strings giving the IP addresses of nameservers for the (non-system) resolver.

In the environment variable, these strings are separated by commas.

Resolver Behaviour

blocking

Ignored

Threaded

Ignored

dnspython

If this setting is not given, the dnspython resolver will
load nameservers to use from /etc/resolv.conf
or the Windows registry. This setting replaces any nameservers read
from those means. Note that the file and registry are still read
for other settings.

Caution

dnspython does not validate the members of the list.
An improper address (such as a hostname instead of IP) has
undefined results, including hanging the process.

ares

Similar to dnspython, but with more platform and compile-time
options. ares validates that the members of the list are valid
addresses.

This is an importable value. It can be given as a string naming an importable object, or a list of strings in preference order and the first successfully importable object will be used. (Separate values in the environment variable with commas.) It can also be given as the callable object itself (in code).