gevent – common functions

The most common functions and classes are available in the gevent top level package.

Please read Introduction for an introduction to the concepts discussed here.

See also

gevent.util

See also

Configuring gevent

For configuring gevent using the environment or the gevent.config object.

__version__ = '22.10.2'

The human-readable PEP 440 version identifier. Use pkg_resources.parse_version(__version__) or packaging.version.Version(__version__) to get a machine-usable value.

Working With Greenlets

See gevent.Greenlet for more information about greenlet objects.

Creating Greenlets

spawn(function, *args, **kwargs) Greenlet

Create a new Greenlet object and schedule it to run function(*args, **kwargs). This can be used as gevent.spawn or Greenlet.spawn.

The arguments are passed to Greenlet.__init__().

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

spawn_later(seconds, function, *args, **kwargs) Greenlet

Create and return a new Greenlet object scheduled to run function(*args, **kwargs) in a future loop iteration seconds later. This can be used as Greenlet.spawn_later or gevent.spawn_later.

The arguments are passed to Greenlet.__init__().

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.

spawn_raw(function, *args, **kwargs)[source]

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.

Changed in version 1.3b1: Only populate spawning_greenlet and spawn_tree_locals if GEVENT_TRACK_GREENLET_TREE is enabled (the default). If not enabled, those attributes will not be set.

Changed in version 1.5a3: The returned greenlet always has a loop attribute matching the current hub’s loop. This helps it work better with more gevent APIs.

Getting Greenlets

getcurrent()

Return the currently executing greenlet (the one that called this function). Note that this may be an instance of Greenlet or greenlet.greenlet.

Stopping Greenlets

kill(greenlet, exception=GreenletExit)[source]

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.

killall(greenlets, exception=GreenletExit, block=True, timeout=None)[source]

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 hub, which should be the hub for this current thread. If this is a generator or iterator that switches greenlets, the results are undefined.

  • exception – The type of 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.

Changed in version 1.5a3: Any Greenlet in the greenlets list that hadn’t been switched to before calling this method will never be switched to. This makes this function behave like Greenlet.kill(). This does not apply to raw greenlets.

Changed in version 1.5a3: Now accepts raw greenlets created by gevent.spawn_raw().

Sleeping

sleep(seconds=0, ref=True)[source]

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.

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

See also

idle()

idle(priority=0)[source]

Cause the calling greenlet to wait until the event loop is idle.

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.

See also

sleep()

Switching

getswitchinterval() current switch interval

See setswitchinterval()

New in version 1.3.

setswitchinterval(seconds)

Set the approximate maximum amount of time that callback functions will be allowed to run before the event loop is cycled to poll for events. This prevents code that does things like the following from monopolizing the loop:

while True: # Burning CPU!
    gevent.sleep(0) # But yield to other greenlets

Prior to this, this code could prevent the event loop from running.

On Python 3, this uses the native sys.setswitchinterval() and sys.getswitchinterval().

New in version 1.3.

Waiting

wait(objects=None, timeout=None, count=None)

Wait for objects to become ready or for event loop to finish.

If objects is provided, it must be a list containing objects implementing the wait protocol (rawlink() and unlink() methods):

If objects is None (the default), wait() blocks until the current event loop has nothing to do (or until timeout passes):

  • all greenlets have finished

  • all servers were stopped

  • all event loop watchers were stopped.

If count is None (the default), wait for all objects to become ready.

If count is a number, wait for (up to) count objects 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.

See also

iwait()

iwait(objects, timeout=None, count=None)

Iteratively yield objects as they are ready, until all (or count) are ready or timeout expired.

If you will only be consuming a portion of the objects, you should do so inside a with block on this object to avoid leaking resources:

with gevent.iwait((a, b, c)) as it:
    for i in it:
        if i is a:
            break
Parameters:
  • objects – A sequence (supporting len()) containing objects implementing the wait protocol (rawlink() and unlink()).

  • count (int) – If not None, then a number specifying the maximum number of objects to wait for. If None (the default), all objects are waited for.

  • timeout (float) – If given, specifies a maximum number of seconds to wait. If the timeout expires before the desired waited-for objects are available, then this method returns immediately.

See also

wait()

Changed in version 1.1a1: Add the count parameter.

Changed in version 1.1a2: No longer raise LoopExit if our caller switches greenlets in between items yielded by this function.

Changed in version 1.4: Add support to use the returned object as a context manager.

joinall(greenlets, timeout=None, raise_error=False, count=None)[source]

Wait for the greenlets to finish.

Parameters:
  • greenlets – A sequence (supporting len()) of greenlets to wait for.

  • timeout (float) – If given, the maximum number of seconds to wait.

Returns:

A sequence of the greenlets that finished before the timeout (if any) expired.

Working with multiple processes

Note

These functions will only be available if os.fork() is available. In general, prefer to use gevent.os.fork() instead of manually calling these functions.

fork(*args, **kwargs)[source]

Forks a child process and starts a child watcher for it in the parent process so that waitpid and SIGCHLD work as expected.

This implementation of fork is a wrapper for fork_and_watch() when the environment variable GEVENT_NOWAITPID is not defined. This is the default and should be used by most applications.

Changed in version 1.1b2.

reinit() None[source]

Prepare the gevent hub to run in a new (forked) process.

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 event loop watchers in the child process.

Signals

signal_handler(signalnum, handler, *args, **kwargs) object

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. It’s best to keep the returned object alive until you call cancel.

Note

This may not operate correctly with SIGCHLD if libev child watchers are used (as they are by default with gevent.os.fork). See gevent.signal for a more general purpose solution.

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

Changed in version 20.5.1: The cancel method now properly cleans up all native resources, and drops references to all the arguments of this function.

Timeouts

See class gevent.Timeout for information about Timeout objects.

with_timeout(seconds, function, *args, **kwds)[source]

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: Greenlet Objects