pax_global_header 0000666 0000000 0000000 00000000064 13115240175 0014511 g ustar 00root root 0000000 0000000 52 comment=b0dec2f86c57e05a6f1697a33f6f5480bb77efc9
gevent-1.2.2/ 0000775 0000000 0000000 00000000000 13115240175 0013003 5 ustar 00root root 0000000 0000000 gevent-1.2.2/.github/ 0000775 0000000 0000000 00000000000 13115240175 0014343 5 ustar 00root root 0000000 0000000 gevent-1.2.2/.github/ISSUE_TEMPLATE.md 0000664 0000000 0000000 00000000501 13115240175 0017044 0 ustar 00root root 0000000 0000000 * gevent version:
* Python version:
* Operating System:
### Description:
```
// REPLACE ME: What are you trying to get done, what has happened, what went wrong, and what did you expect?
```
### What I've run:
```
// REPLACE ME: Paste short, self contained, correct example code (sscce.org), tracebacks, etc, here
```
gevent-1.2.2/.gitignore 0000664 0000000 0000000 00000002500 13115240175 0014770 0 ustar 00root root 0000000 0000000 *.py[cod]
build/
.runtimes
.tox/
*.so
*.o
*.egg-info
gevent.*.[ch]
src/gevent/libev/corecext.pyx
src/gevent/__pycache__
src/gevent/libev/_corecffi.c
src/gevent/libev/_corecffi.o
Makefile.ext
MANIFEST
*_flymake.py
src/greentest/.coverage\.*
src/greentest/htmlcov
src/greentest/.coverage
doc/_build
doc/__pycache__
doc/gevent.*.rst
!doc/gevent.core.rst
!doc/gevent.event.rst
!doc/gevent.hub.rst
!doc/gevent.queue.rst
!doc/gevent.pool.rst
!doc/gevent.threadpool.rst
!doc/gevent.socket.rst
!doc/gevent.ssl.rst
!doc/gevent.wsgi.rst
# Artifacts of configuring in place
deps/c-ares/config.log
deps/c-ares/config.status
deps/c-ares/stamp-h1
deps/c-ares/stamp-h2
deps/c-ares/ares_build.h.orig
deps/c-ares/ares_config.h
deps/c-ares/.libs
deps/c-ares/*.o
deps/c-ares/*.lo
deps/c-ares/*.la
deps/c-ares/.deps
deps/c-ares/acountry
deps/c-ares/adig
deps/c-ares/ahost
deps/c-ares/Makefile
deps/c-ares/libtool
deps/c-ares/libcares.pc
deps/c-ares/test/.deps
deps/c-ares/test/Makefile
deps/c-ares/test/config.log
deps/c-ares/test/config.status
deps/c-ares/test/libtool
deps/c-ares/test/stamp-h1
deps/libev/.deps
deps/libev/Makefile
deps/libev/config.log
deps/libev/config.h
deps/libev/config.status
deps/libev/libtool
deps/libev/stamp-h1
deps/libev/.libs
deps/libev/*.lo
deps/libev/*.la
deps/libev/*.o
# running setup.py on PyPy
config.h
configure-output.txt
gevent-1.2.2/.landscape.yml 0000664 0000000 0000000 00000007500 13115240175 0015540 0 ustar 00root root 0000000 0000000 doc-warnings: no # experimental, raises an exception
test-warnings: no
strictness: veryhigh
max-line-length: 160
# We don't use any of the auto-detected things, and
# auto-detection slows down startup
autodetect: false
requirements:
- dev-requirements.txt
python-targets:
- 2
# - 3 # landscape.io seems to fail if we run both py2 and py3?
ignore-paths:
- examples/webchat/
- doc/
- build/
- deps/
- dist
- .eggs
# util creates lots of warnings. ideally they should be fixed,
# but that code doesn't change often
- util
# likewise with scripts
- scripts/
# This file has invalid syntax for Python 3, which is how
# landscape.io runs things...
- src/gevent/_util_py2.py
# ...and this file has invalid syntax for Python 2, which is how
# travis currently runs things. sigh.
- src/gevent/_socket3.py
# This is vendored with minimal changes
- src/gevent/_tblib.py
# likewise
- src/greentest/_six.py
# This triggers https://github.com/PyCQA/pylint/issues/846 on Travis,
# but the file is really small, so it's better to skip this one
# file than disable that whole check.
- src/gevent/core.py
# sadly, this one is complicated
- setup.py
# This crashes (infinite recursion) trying to get the mro() of a class that extends
# build_ext
- _setuputils.py
- src/greentest/getaddrinfo_module.py
ignore-patterns:
# disabled code
- ^src/greentest/xtest_.*py
# standard library code
- ^src/greentest/2.*
- ^src/greentest/3.*
# benchmarks that aren't used/changed much
- ^src/greentest/bench_.*py
pyroma:
run: true
mccabe:
# We have way too many violations of the complexity measure.
# We should enable this and fix them one at a time, but that's
# more refactoring than I want to do initially.
run: false
pyflakes:
disable:
# F821: undefined name; caught better by pylint, where it can be
# controlled for the whole file/per-line
- F821
# F401: unused import; same story
- F401
# F811: redefined function; same story
- F811
# F403: wildcard import; same story
- F403
pep8:
disable:
# N805: first arg should be self; fails on metaclasses and
# classmethods; pylint does a better job
- N805
# N802: function names should be lower-case; comes from Windows
# funcs and unittest-style asserts and factory funcs
- N802
# N801: class names should use CapWords
- N801
# N803: argument name should be lower-case; comes up with using
# the class name as a keyword-argument
- N803
# N813: camelCase imported as lowercase; socketcommon
- N813
# N806: variable in function should be lowercase; but sometimes we
# want constant-looking names, especially for closures
- N806
# N812: lowercase imported as non-lowercase; from greenlet import
# greenlet as RawGreenlet
- N812
# E261: at least two spaces before inline comment. Really? Who does
# that?
- E261
# E265: Block comment should start with "# ". This arises from
# commenting out individual lines of code.
- E265
# N806: variable in function should be lowercase; but sometimes we
# want constant-looking names, especially for closures
- N806
# W503 line break before binary operator (I like and/or on the
# next line, it makes more sense)
- W503
# E266: too many leading '#' for block comment. (Multiple # can
# set off blocks)
- E266
# E402 module level import not at top of file. (happens in
# setup.py, some test cases)
- E402
# E702: multiple expressions on one line semicolon
# (happens for monkey-patch))
- E702
# E731: do not assign a lambda expression, use a def
# simpler than a def sometimes, and prevents redefinition warnings
- E731
# E302/303: Too many/too few blank lines (between classes, etc)
# This is *really* nitpicky.
- E302
- E303
gevent-1.2.2/.pylintrc 0000664 0000000 0000000 00000007544 13115240175 0014662 0 ustar 00root root 0000000 0000000
[MESSAGES CONTROL]
# Disable the message, report, category or checker with the given id(s). You
# can either give multiple identifier separated by comma (,) or put this option
# multiple time (only on the command line, not in the configuration file where
# it should appear only once).
# NOTE: comments must go ABOVE the statement. In Python 2, mixing in
# comments disables all directives that follow, while in Python 3, putting
# comments at the end of the line does the same thing (though Py3 supports
# mixing)
# invalid-name, ; We get lots of these, especially in scripts. should fix many of them
# protected-access, ; We have many cases of this; legit ones need to be examinid and commented, then this removed
# no-self-use, ; common in superclasses with extension points
# too-few-public-methods, ; Exception and marker classes get tagged with this
# exec-used, ; should tag individual instances with this, there are some but not too many
# global-statement, ; should tag individual instances
# multiple-statements, ; "from gevent import monkey; monkey.patch_all()"
# locally-disabled, ; yes, we know we're doing this. don't replace one warning with another
# cyclic-import, ; most of these are deferred imports
# too-many-arguments, ; these are almost always because that's what the stdlib does
# redefined-builtin, ; likewise: these tend to be keyword arguments like len= in the stdlib
# undefined-all-variable, ; XXX: This crashes with pylint 1.5.4 on Travis (but not locally on Py2/3
# ; or landscape.io on Py3). The file causing the problem is unclear. UPDATE: identified and disabled
# that file.
# see https://github.com/PyCQA/pylint/issues/846
# useless-suppression: the only way to avoid repeating it for specific statements everywhere that we
# do Py2/Py3 stuff is to put it here. Sadly this means that we might get better but not realize it.
# duplicate-code: Yeah, the compatibility ssl modules are much the same
disable=wrong-import-position,
wrong-import-order,
missing-docstring,
ungrouped-imports,
invalid-name,
protected-access,
no-self-use,
too-few-public-methods,
exec-used,
global-statement,
multiple-statements,
locally-disabled,
cyclic-import,
too-many-arguments,
redefined-builtin,
useless-suppression,
duplicate-code,
undefined-all-variable
[FORMAT]
# duplicated from setup.cfg
max-line-length=160
max-module-lines=1070
[MISCELLANEOUS]
# List of note tags to take in consideration, separated by a comma.
#notes=FIXME,XXX,TODO
# Disable that, we don't want them in the report (???)
notes=
[VARIABLES]
dummy-variables-rgx=_.*
[TYPECHECK]
# List of members which are set dynamically and missed by pylint inference
# system, and so shouldn't trigger E1101 when accessed. Python regular
# expressions are accepted.
# gevent: this is helpful for py3/py2 code.
generated-members=exc_clear
# List of classes names for which member attributes should not be checked
# (useful for classes with attributes dynamically set). This supports can work
# with qualified names.
# greenlet, Greenlet, parent, dead: all attempts to fix issues in greenlet.py
# only seen on the service, e.g., self.parent.loop: class parent has no loop
ignored-classes=SSLContext, SSLSocket, greenlet, Greenlet, parent, dead
# List of module names for which member attributes should not be checked
# (useful for modules/projects where namespaces are manipulated during runtime
# and thus existing member attributes cannot be deduced by static analysis. It
# supports qualified module names, as well as Unix pattern matching.
ignored-modules=gevent._corecffi,gevent.os,os,greenlet,threading,gevent.libev.corecffi
[DESIGN]
max-attributes=12
[BASIC]
bad-functions=input
# Prospector turns ot unsafe-load-any-extension by default, but
# pylint leaves it off. This is the proximal cause of the
# undefined-all-variable crash.
#unsafe-load-any-extension = no
gevent-1.2.2/.travis.yml 0000664 0000000 0000000 00000001622 13115240175 0015115 0 ustar 00root root 0000000 0000000 # .travis.yml based on https://github.com/DRMacIver/hypothesis/blob/master/.travis.yml
language: c
sudo: false
dist: trusty
env:
global:
- BUILD_RUNTIMES=$HOME/.runtimes
matrix:
# These are ordered to get as much diversity in the
# first group of parallel runs (4) as posible
- TASK=test-py27-noembed
- TASK=test-pypy
- TASK=test-py36
- TASK=lint-py27
- TASK=test-pypy3
- TASK=test-py35
- TASK=test-py278
- TASK=test-py27
- TASK=test-py34
- TASK=test-py27-cffi
matrix:
fast_finish: true
script:
- make $TASK
notifications:
email: false
# cache: pip seems not to work if `install` is replaced (https://github.com/travis-ci/travis-ci/issues/3239)
cache:
directories:
- $HOME/.cache/pip
- $HOME/.venv
- $HOME/.runtimes
- $HOME/.wheelhouse
before_cache:
- rm -f $HOME/.cache/pip/log/debug.log
gevent-1.2.2/AUTHORS 0000664 0000000 0000000 00000002372 13115240175 0014057 0 ustar 00root root 0000000 0000000 Gevent is written and maintained by
Denis Bilenko
Matt Iversen
Steffen Prince
Jason Madden
and the contributors (ordered by the date of first contribution):
Jason Toffaletti
Mike Barton
Ludvig Ericson
Marcus Cavanaugh
Matt Goodall
Ralf Schmitt
Daniele Varrazzo
Nicholas Piël
Örjan Persson
Uriel Katz
Ted Suzman
Randall Leeds
Erik Näslund
Alexey Borzenkov
David Hain
Dmitry Chechik
Ned Rockson
Tommie Gannert
Shaun Lindsay
Andreas Blixt
Nick Barkas
Galfy Pundee
Alexander Boudkar
Damien Churchill
Tom Lynn
Shaun Cutts
David LaBissoniere
Alexandre Kandalintsev
Geert Jansen
Vitaly Kruglikov
Saúl Ibarra Corretgé
Oliver Beattie
Bobby Powers
Anton Patrushev
Jan-Philip Gehrcke
Alex Gaynor
陈小玉
Philip Conrad
See https://github.com/gevent/gevent/graphs/contributors for more info.
Gevent is inspired by and uses some code from eventlet which was written by
Bob Ipollito
Donovan Preston
The win32util module is taken from Twisted. The tblib module is taken from python-tblib by Ionel Cristian Mărieș.
Some modules (local, ssl) contain code from the Python standard library.
If your code is used in gevent and you are not mentioned above, please contact the maintainer.
gevent-1.2.2/CHANGES.rst 0000664 0000000 0000000 00000320721 13115240175 0014612 0 ustar 00root root 0000000 0000000 ===========
Changelog
===========
.. currentmodule:: gevent
1.2.2 (2017-06-05)
==================
- Testing on Python 3.5 now uses Python 3.5.3 due to SSL changes. See
:issue:`943`.
- Linux CI has been updated from Ubuntu 12.04 to Ubuntu 14.04 since
the former has reached EOL.
- Linux CI now tests on PyPy2 5.7.1, updated from PyPy2 5.6.0.
- Linux CI now tests on PyPy3 3.5-5.7.1-beta, updated from PyPy3
3.3-5.5-alpha.
- Python 2 sockets are compatible with the ``SOCK_CLOEXEC`` flag found
on Linux. They no longer pass the socket type or protocol to
``getaddrinfo`` when ``connect`` is called. Reported in :issue:`944`
by Bernie Hackett.
- Replace ``optparse`` module with ``argparse``. See :issue:`947`.
- Update to version 1.3.1 of ``tblib`` to fix :issue:`954`,
reported by ml31415.
- Fix the name of the ``type`` parameter to
:func:`gevent.socket.getaddrinfo` to be correct on Python 3. This
would cause callers using keyword arguments to raise a :exc:`TypeError`.
Reported in :issue:`960` by js6626069. Likewise, correct the
argument names for ``fromfd`` and ``socketpair`` on Python 2,
although they cannot be called with keyword arguments under CPython.
.. note:: The ``gethost*`` functions take different argument names
under CPython and PyPy. gevent follows the CPython
convention, although these functions cannot be called with
keyword arguments on CPython.
- The previously-singleton exception objects ``FileObjectClosed`` and
``cancel_wait_ex`` were converted to classes. On Python 3, an
exception object is stateful, including references to its context
and possibly traceback, which could lead to objects remaining alive
longer than intended.
- Make sure that ``python -m gevent.monkey
You're also welcome to join `#gevent`_ IRC channel on freenode.
Russian group
-------------
Русскоязычная группа находится здесь: `Google Groups (gevent-ru)`_. Чтобы подписаться, отправьте сообщение на gevent-ru+subscribe@googlegroups.com
.. _Google Groups (gevent): http://groups.google.com/group/gevent
.. _#gevent: http://webchat.freenode.net/?channels=gevent
.. _Google Groups (gevent-ru): http://groups.google.com/group/gevent-ru
gevent-1.2.2/doc/conf.py 0000664 0000000 0000000 00000020051 13115240175 0015045 0 ustar 00root root 0000000 0000000 # -*- coding: utf-8 -*-
#
# gevent documentation build configuration file, created by
# sphinx-quickstart on Thu Oct 1 09:30:02 2009.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
from __future__ import print_function
import sys
import os
os.system('%s generate_rst.py generate' % sys.executable)
sys.path.append('.') # for mysphinxext
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.append(os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.doctest', 'sphinx.ext.coverage', 'sphinx.ext.intersphinx', 'mysphinxext',
'sphinx.ext.extlinks']
intersphinx_mapping = {'http://docs.python.org/': None,
'https://greenlet.readthedocs.io/en/latest/': None}
extlinks = {'issue': ('https://github.com/gevent/gevent/issues/%s',
'issue #'),
'pr': ('https://github.com/gevent/gevent/pull/%s',
'pull request #')}
autodoc_default_flags = ['members', 'show-inheritance']
autoclass_content = 'both'
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8'
# The master toctree document.
master_doc = 'contents'
# General information about the project.
project = u'gevent'
copyright = u'2009-2015, gevent contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
from gevent import __version__
version = __version__
# The full version, including alpha/beta/rc tags.
release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# List of directories, relative to source directory, that shouldn't be searched
# for source files.
exclude_trees = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
add_module_names = False
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'perldoc'
# A list of ignored prefixes for module index sorting.
modindex_common_prefix = ['gevent.']
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. Major themes that come with
# Sphinx are currently 'default' and 'sphinxdoc'.
html_theme = 'mytheme'
html_theme_path = ['.']
html_theme_options = {'gevent_version': __version__}
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#if html_theme == 'default':
# html_theme_options = {'rightsidebar' : True}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
html_short_title = 'Documentation'
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
#html_static_path = ['_static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {'contentstable': 'contentstable.html'}
# If false, no module index is generated.
html_use_modindex = True
# If false, no index is generated.
html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = ''
# Output file base name for HTML help builder.
htmlhelp_basename = 'geventdoc'
# -- Options for LaTeX output --------------------------------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'gevent.tex', u'gevent Documentation',
u'gevent contributors', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
###############################################################################
# prevent some stuff from showing up in docs
import socket
import gevent.socket
del gevent.Greenlet.throw
for item in gevent.socket.__all__[:]:
if getattr(gevent.socket, item) is getattr(socket, item, None):
gevent.socket.__all__.remove(item)
# order the methods in the class documentation the same way they are ordered in the source code
from sphinx.ext import autodoc
from sphinx.ext.autodoc import ClassDocumenter
class MyClassDocumenter(ClassDocumenter):
def get_object_members(self, want_all):
members_check_module, members = super(MyClassDocumenter, self).get_object_members(want_all)
def key((name, obj)):
try:
return obj.im_func.func_code.co_firstlineno
except AttributeError:
return 0
members.sort(key=key)
return members_check_module, members
autodoc.ClassDocumenter = MyClassDocumenter
gevent-1.2.2/doc/contents.rst 0000664 0000000 0000000 00000000273 13115240175 0016141 0 ustar 00root root 0000000 0000000 Table Of Contents
=================
.. toctree::
intro
whatsnew_1_2
reference
whatsnew_1_1
whatsnew_1_0
changelog
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
gevent-1.2.2/doc/dns.rst 0000664 0000000 0000000 00000002561 13115240175 0015072 0 ustar 00root root 0000000 0000000 =======================
Name Resolution (DNS)
=======================
gevent includes support for a pluggable hostname resolution system.
Pluggable resolvers are (generally) intended to be cooperative.
This pluggable resolution system is used automatically when the system
is :mod:`monkey patched `, and may be used manually
through the :attr:`resolver attribute ` of the
:class:`gevent.hub.Hub` or the corresponding methods in the
:mod:`gevent.socket` module.
A resolver implements the 5 standandard functions from the
:mod:`socket` module for resolving hostnames:
* :func:`socket.gethostbyname`
* :func:`socket.gethostbyname_ex`
* :func:`socket.getaddrinfo`
* :func:`socket.gethostbyaddr`
* :func:`socket.getnameinfo`
Configuration
=============
gevent includes three implementations of resolvers, and applications
can provide their own implementation. By default, gevent uses
:class:`gevent.resolver_thread.Resolver`.
Configuration can be done through the ``GEVENT_RESOLVER`` environment
variable. Specify ``ares``, ``thread``, or ``block`` to use the
:class:`gevent.resolver_ares.Resolver`,
:class:`gevent.resolver_thread.Resolver`, or
:class:`gevent.socket.BlockingResolver`, respectively, or set it to
the fully-qualified name of an implementation of the standard
functions.
.. toctree::
gevent.resolver_thread
gevent.resolver_ares
gevent-1.2.2/doc/generate_rst.py 0000775 0000000 0000000 00000007177 13115240175 0016623 0 ustar 00root root 0000000 0000000 #!/usr/bin/env python
from __future__ import print_function
import os
import glob
from os.path import join, dirname, abspath, basename
# do not generate .rst for the following modules as they imported into gevent package
# and covered there
SKIP = ['hub', 'timeout', 'greenlet']
template = '''.. AUTOGENERATED -- will be overwritten (remove this comment to save changes)
%(title)s
%(title_underline)s
.. automodule:: gevent.%(module)s
:members:
:undoc-members:
'''
def _find_modules():
try:
import gevent
except ImportError:
print("Failed to import gevent, no modules found")
return ()
directory = dirname(abspath(gevent.__file__))
print('Imported gevent from %s' % (directory, ))
modules = glob.glob(join(directory, '*.py')) + glob.glob(join(directory, '*.pyc'))
modules = set(basename(filename).split('.')[0] for filename in modules)
modules = set(name for name in modules
if name.startswith('_socket2') or name.startswith('_socket3') or name.startswith('_ssl')
or not name.startswith('_'))
return modules
import warnings
warnings.simplefilter('ignore', DeprecationWarning)
modules = _find_modules()
def _read(fname, count):
with open(fname) as f:
return f.read(count)
def generate_rst_for_module(module, do=True):
rst_filename = 'gevent.%s.rst' % module
exists = os.path.exists(rst_filename)
if exists:
autogenerated = 'autogenerated' in _read(rst_filename, 200).lower()
if not autogenerated:
return
m = __import__('gevent.%s' % module)
m = getattr(m, module)
title = getattr(m, '__doc__', None)
if title:
lines = title.strip().splitlines()
for line in lines:
# skip leading blanks. Support both styles of docstrings.
if line:
title = line.strip()
break
title = title.strip(' .')
prefix = ':mod:`gevent.%s`' % module
if title:
title = prefix + ' -- %s' % (title, )
else:
title = prefix
title_underline = '=' * len(title)
params = globals().copy()
params.update(locals())
result = template % params
if getattr(m, '_no_undoc_members', True):
result = '\n'.join(result.splitlines()[:-1])
if exists:
if _read(rst_filename, len(result) + 1) == result:
return # already exists one which is the same
if do:
print('Generated %s from %s' % (rst_filename, m.__file__))
with open(rst_filename, 'w') as f:
f.write(result)
else:
print('Would generate %s from %s' % (rst_filename, m.__file__))
def generate_rst(do=True):
assert os.path.exists('contents.rst'), 'Wrong directory, contents.rst not found'
for module in modules:
if module not in SKIP:
generate_rst_for_module(module, do=do)
def iter_autogenerated():
for module in modules:
rst_filename = 'gevent.%s.rst' % module
exists = os.path.exists(rst_filename)
if exists:
autogenerated = 'autogenerated' in open(rst_filename).read(200).lower()
if autogenerated:
yield rst_filename
if __name__ == '__main__':
import sys
if sys.argv[1:] == ['show']:
for filename in iter_autogenerated():
print(filename)
elif sys.argv[1:] == ['delete']:
for filename in iter_autogenerated():
print('Removing', filename)
os.unlink(filename)
elif sys.argv[1:] == ['generate']:
generate_rst()
elif sys.argv[1:] == []:
generate_rst(do=False)
else:
sys.exit('Invalid command line: %s' % (sys.argv[1:], ))
gevent-1.2.2/doc/gevent.core.rst 0000664 0000000 0000000 00000002343 13115240175 0016523 0 ustar 00root root 0000000 0000000 :mod:`gevent.core` - event loop based on libev
==============================================
.. automodule:: gevent.core
This module is a wrapper around libev__ and follower the libev API pretty closely. Note,
that gevent creates an event loop transparently for the user and runs it in a dedicated
greenlet (called hub), so using this module is not necessary. In fact, if you do use it,
chances are that your program is not compatible across different gevent version (gevent.core in
0.x has a completely different interface and 2.x will probably have yet another interface).
On Windows, this wrapper will accept Windows handles rather than stdio file descriptors which libev requires. This is to simplify
interaction with the rest of the Python, since it requires Windows handles.
The current event loop can be obtained with ``gevent.get_hub().loop``.
__ http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod
events
------
.. autoclass:: loop(flags=None, default=True)
:members:
:undoc-members:
misc functions
--------------
.. autofunction:: get_version
.. autofunction:: get_header_version
.. autofunction:: supported_backends
.. autofunction:: recommended_backends
.. autofunction:: embeddable_backends
.. autofunction:: time
gevent-1.2.2/doc/gevent.event.rst 0000664 0000000 0000000 00000000667 13115240175 0016723 0 ustar 00root root 0000000 0000000 :mod:`gevent.event` -- Notifications of multiple listeners
==========================================================
.. module:: gevent.event
.. autoclass:: gevent.event.Event
:members: set, clear, wait, rawlink, unlink
.. method:: is_set()
isSet()
ready()
Return true if and only if the internal flag is true.
.. autoclass:: gevent.event.AsyncResult
:members:
:undoc-members:
gevent-1.2.2/doc/gevent.hub.rst 0000664 0000000 0000000 00000000407 13115240175 0016350 0 ustar 00root root 0000000 0000000 ====================================
:mod:`gevent.hub` - Event-loop hub
====================================
.. module:: gevent.hub
.. autofunction:: get_hub
.. autoclass:: Hub
:members:
:undoc-members:
.. autoclass:: Waiter
.. autoclass:: LoopExit
gevent-1.2.2/doc/gevent.pool.rst 0000664 0000000 0000000 00000000277 13115240175 0016550 0 ustar 00root root 0000000 0000000 :mod:`gevent.pool` -- Managing greenlets in a group
===================================================
.. automodule:: gevent.pool
:members:
:undoc-members:
:inherited-members:
gevent-1.2.2/doc/gevent.queue.rst 0000664 0000000 0000000 00000001233 13115240175 0016714 0 ustar 00root root 0000000 0000000 :mod:`gevent.queue` -- Synchronized queues
==========================================
.. automodule:: gevent.queue
:members:
:undoc-members:
.. exception:: Full
An alias for :class:`Queue.Full`
.. exception:: Empty
An alias for :class:`Queue.Empty`
Example of how to wait for enqueued tasks to be completed::
def worker():
while True:
item = q.get()
try:
do_work(item)
finally:
q.task_done()
q = JoinableQueue()
for i in range(num_worker_threads):
gevent.spawn(worker)
for item in source():
q.put(item)
q.join() # block until all tasks are done
gevent-1.2.2/doc/gevent.rst 0000664 0000000 0000000 00000013232 13115240175 0015573 0 ustar 00root root 0000000 0000000 ==================================
:mod:`gevent` -- basic utilities
==================================
.. module:: gevent
The most common functions and classes are available in the :mod:`gevent` top level package.
.. autodata:: __version__
.. autodata:: version_info
Greenlet objects
================
:class:`Greenlet` is a light-weight cooperatively-scheduled execution unit.
To start a new greenlet, pass the target function and its arguments to :class:`Greenlet` constructor and call :meth:`start`:
>>> g = Greenlet(myfunction, 'arg1', 'arg2', kwarg1=1)
>>> g.start()
or use classmethod :meth:`spawn` which is a shortcut that does the same:
>>> g = Greenlet.spawn(myfunction, 'arg1', 'arg2', kwarg1=1)
To subclass a :class:`Greenlet`, override its ``_run()`` method and
call ``Greenlet.__init__(self)`` in :meth:`__init__`: It also a good
idea to override :meth:`__str__`: if :meth:`_run` raises an exception,
its string representation will be printed after the traceback it
generated.
.. important:: You *SHOULD NOT* attempt to override the ``run()`` method.
.. class:: Greenlet
.. automethod:: Greenlet.__init__
.. attribute:: Greenlet.value
Holds the value returned by the function if the greenlet has
finished successfully. Until then, or if it finished in error, ``None``.
.. tip:: Recall that a greenlet killed with the default
:class:`GreenletExit` is considered to have finished
successfully, and the ``GreenletExit`` exception will be
its value.
.. autoattribute:: Greenlet.exception
.. automethod:: Greenlet.ready
.. automethod:: Greenlet.successful
.. automethod:: Greenlet.start
.. automethod:: Greenlet.start_later
.. automethod:: Greenlet.join
.. automethod:: Greenlet.get
.. automethod:: Greenlet.kill(exception=GreenletExit, block=True, timeout=None)
.. automethod:: Greenlet.link(callback)
.. automethod:: Greenlet.link_value(callback)
.. automethod:: Greenlet.link_exception(callback)
.. automethod:: Greenlet.rawlink
.. automethod:: Greenlet.unlink
Boolean Contexts
----------------
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(...)
>>> while g:
# do something while g is alive
The Greenlet's ``__nonzero__`` is an improvement on greenlet's
``__nonzero__``. The greenlet's :meth:`__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.
Raw greenlet Methods
--------------------
Being a greenlet__ subclass, :class:`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 :class:`Event ` and :class:`Queue
`, instead.
__ https://greenlet.readthedocs.io/en/latest/#instantiation
.. _switching: https://greenlet.readthedocs.io/en/latest/#switching
.. _throw: https://greenlet.readthedocs.io/en/latest/#methods-and-attributes-of-greenlets
.. exception:: GreenletExit
A special exception that kills the greenlet silently.
When a greenlet raises :exc:`GreenletExit` or a subclass, the traceback is not
printed and the greenlet is considered :meth:`successful `.
The exception instance is available under :attr:`value `
property as if it was returned by the greenlet, not raised.
Spawn helpers
=============
.. autofunction:: spawn(function, *args, **kwargs)
.. autofunction:: spawn_later(seconds, function, *args, **kwargs)
.. autofunction:: spawn_raw
Useful general functions
========================
.. function:: getcurrent()
Return the currently executing greenlet (the one that called this
function). Note that this may be an instance of :class:`Greenlet`
or :class:`greenlet.greenlet`.
Sleeping
--------
.. autofunction:: sleep
.. autofunction:: idle
Stopping Greenlets
------------------
.. autofunction:: kill(greenlet, exception=GreenletExit)
.. autofunction:: killall(greenlets, exception=GreenletExit, block=True, timeout=None)
Waiting
-------
.. autofunction:: wait
.. autofunction:: iwait
.. autofunction:: joinall
Working with muliple processes
------------------------------
.. autofunction:: fork
.. autofunction:: reinit
Signals
-------
.. function:: signal(signalnum, handler, *args, **kwargs)
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 :func:`gevent.os.fork`).
.. versionchanged:: 1.1b4
This is an alias for ``gevent.hub.signal``, included for
backwards compatibility; the new module :doc:`gevent.signal `
is replacing this name. This alias will be removed in a
future release.
.. versionchanged:: 1.2a1
The *handler* is required to be callable at construction time.
.. This is also in the docstring of gevent.hub.signal, which is the
actual callable invoked
Timeouts
========
.. autoclass:: Timeout
:members:
:undoc-members:
.. autofunction:: with_timeout
gevent-1.2.2/doc/gevent.socket.rst 0000664 0000000 0000000 00000005652 13115240175 0017071 0 ustar 00root root 0000000 0000000 ====================================================================
:mod:`gevent.socket` -- Cooperative low-level networking interface
====================================================================
This module provides socket operations and some related functions. The
API of the functions and classes matches the API of the corresponding
items in the standard :mod:`socket` module exactly, but the
synchronous functions in this module only block the current greenlet
and let the others run.
.. tip:: gevent's sockets, like most gevent objects, have thread
affinity. That is, they can only be used from the operating
system thread that created them (any greenlet in that thread
can use the socket). The results of attempting to use the
socket in another thread (for example, passing it to the
threadpool) are not defined (but one common outcome is a
:exc:`~gevent.hub.LoopExit` exception).
For convenience, exceptions (like :class:`error ` and
:class:`timeout `) as well as the constants from the
:mod:`socket` module are imported into this module. In almost all
cases one can simply replace ``import socket`` with ``from gevent
import socket`` to start using cooperative sockets with no other
changes (or use :func:`gevent.monkey.patch_socket` at startup if code
changes are not desired or possible).
Standard Library Interface
==========================
The exact API exposed by this module varies depending on what version
of Python you are using. The documents below describe the API for
Python 2 and Python 3, respectively.
.. note:: All the described APIs should be imported from
``gevent.socket``, and *not* from their implementation modules.
Their organization is an implementation detail that may change at
any time.
.. toctree::
Python 3 interface
Python 2 interface
Gevent Extensions
=================
Beyond the basic standard library interface, ``gevent.socket``
provides some extensions. These are identical and shared by all
versions of Python.
Waiting
-------
These functions are used to block the current greenlet until an open
file (socket) is ready to perform I/O operations. These are low-level
functions not commonly used by many programs.
.. note:: These use the underlying libev ``io`` watchers, which means
that they share the same implementation limits. For example,
on some platforms they can be used with more than just
sockets, while on others the applicability is more limited
(POSIX platforms like Linux and OS X can use pipes and fifos
but Windows is limited to sockets).
.. note:: On Windows, gevent is limited to 1024 open sockets.
.. autofunction:: gevent.socket.wait_read
.. autofunction:: gevent.socket.wait_write
.. autofunction:: gevent.socket.wait_readwrite
.. autofunction:: gevent.socket.wait
.. autofunction:: gevent.socket.cancel_wait
gevent-1.2.2/doc/gevent.ssl.rst 0000664 0000000 0000000 00000002117 13115240175 0016373 0 ustar 00root root 0000000 0000000 ====================================================================
:mod:`gevent.ssl` -- Secure Sockets Layer (SSL/TLS) module
====================================================================
This module provides SSL/TLS operations and some related functions. The
API of the functions and classes matches the API of the corresponding
items in the standard :mod:`ssl` module exactly, but the
synchronous functions in this module only block the current greenlet
and let the others run.
The exact API exposed by this module varies depending on what version
of Python you are using. The documents below describe the API for
Python 3, Python 2.7.9 and above, and Python 2.7.8 and below, respectively.
.. warning:: All the described APIs should be imported from
``gevent.ssl``, and *not* from their implementation modules.
Their organization is an implementation detail that may change at
any time.
.. toctree::
Python 3 interface
Python 2.7.9 and above interface (including PyPy 2.6.1 and above)
Python 2.7.8 and below interface
gevent-1.2.2/doc/gevent.threadpool.rst 0000664 0000000 0000000 00000002416 13115240175 0017735 0 ustar 00root root 0000000 0000000
=====================================================
:mod:`gevent.threadpool` - A pool of native threads
=====================================================
.. currentmodule:: gevent.threadpool
.. autoclass:: ThreadPool
:inherited-members:
:members: imap, imap_unordered, map, map_async, apply_async, kill,
join, spawn
.. method:: apply(func, args=None, kwds=None)
Rough equivalent of the :func:`apply()` builtin function,
blocking until the result is ready and returning it.
The ``func`` will *usually*, but not *always*, be run in a way
that allows the current greenlet to switch out (for example,
in a new greenlet or thread, depending on implementation). But
if the current greenlet or thread is already one that was
spawned by this pool, the pool may choose to immediately run
the `func` synchronously.
.. note:: As implemented, attempting to use
:meth:`Threadpool.appy` from inside another function that
was itself spawned in a threadpool (any threadpool) will
cause the function to be run immediately.
.. versionchanged:: 1.1a2
Now raises any exception raised by *func* instead of
dropping it.
.. autoclass:: ThreadPoolExecutor
gevent-1.2.2/doc/gevent.wsgi.rst 0000664 0000000 0000000 00000001144 13115240175 0016542 0 ustar 00root root 0000000 0000000
==============================================================================
:mod:`gevent.wsgi` -- Backwards compatibility alias for :mod:`gevent.pywsgi`
==============================================================================
In the past, this module used libevent's http support, but that was dropped
with the introduction of libev. libevent's http support had several
limitations, including not supporting stream, not supporting
pipelining, and not supporting SSL.
This module now simply re-exports the contents of the
:mod:`gevent.pywsgi` module.
.. deprecated:: 1.1
Use :mod:`gevent.pywsgi`
gevent-1.2.2/doc/index.rst 0000664 0000000 0000000 00000005122 13115240175 0015411 0 ustar 00root root 0000000 0000000 =================
What is gevent?
=================
gevent is a coroutine_ -based Python_ networking library that uses
greenlet_ to provide a high-level synchronous API on top of the libev
event loop.
Features include:
* **Fast event loop** based on libev (epoll on Linux, kqueue on FreeBSD).
* **Lightweight execution units** based on greenlet.
* API that re-uses concepts from the Python standard library (for example there are :class:`gevent.event.Events` and :class:`gevent.queue.Queues`).
* :doc:`Cooperative sockets with SSL support `
* DNS queries performed through threadpool or c-ares.
* :ref:`Monkey patching utility ` to get 3rd party modules to become cooperative
gevent is `inspired by eventlet
`_ but features more
consistent API, simpler implementation and better performance. Read
why others `use gevent
`_
and check out the list of the `open source projects based on gevent. `_
gevent is written and maintained by `Denis Bilenko
`_ with help from the `contributors `_ and is licensed under the MIT license.
:ref:`Continue reading ` »
If you like gevent, :doc:`donate ` to support the development.
What are others saying?
=======================
Twitter @gevent
---------------
.. raw:: html
Tweets about gevent
Mailing List
------------
.. raw:: html
.. _coroutine: https://en.wikipedia.org/wiki/Coroutine
.. _Python: http://python.org
.. _greenlet: https://greenlet.readthedocs.io
gevent-1.2.2/doc/intro.rst 0000664 0000000 0000000 00000041355 13115240175 0015445 0 ustar 00root root 0000000 0000000 ==============
Introduction
==============
gevent is a coroutine-based Python networking library.
Features include:
* Fast event loop based on libev (epoll on Linux, kqueue on FreeBSD,
select on Mac OS X).
* Lightweight execution units based on greenlet.
* API that re-uses concepts from the Python standard library (e.g. :class:`gevent.event.Event`, :class:`gevent.queue.Queue`).
* Cooperative :mod:`socket` and :mod:`ssl` modules.
* Ability to use standard library and 3rd party modules written for standard blocking sockets (:mod:`gevent.monkey`).
* DNS queries performed through threadpool (default) or through c-ares (enabled via GEVENT_RESOLVER=ares env var).
* TCP/UDP/HTTP servers
* Subprocess support (through :mod:`gevent.subprocess`)
* Thread pools
.. _installation:
Installation and Requirements
=============================
`gevent 1.2`_ runs on Python 2 and Python 3. Version 2.7 of
Python 2 is supported, and versions 3.4, 3.5 and 3.6 of Python 3 are
supported. (Users of older versions of Python 2 need to install gevent
1.0.x (2.5) or 1.1.x (2.6); Python 3 is not supported by 1.0.) gevent requires the
greenlet__ library.
.. note:: Python 3.3 is no longer actively supported since it is not
supported by the Python developers. However, it should
continue to work with gevent 1.2 with the same level of
support as gevent 1.1. For Python 3.3, version 3.3.5 or
newer is required to use the gevent's SSL support due to
bugs in the standard library of older versions. For Python
2, 2.7.9 or newer is recommended for the best SSL support;
2.7.8 is also tested although it offers a less-secure SSL
module.
gevent 1.2 also runs on PyPy 2.6.1 and above, although 5.0 or above is
strongly recommended. On PyPy, there are no external dependencies.
gevent is tested on Windows, OS X, and Linux, and should run on most
other Unix-like operating systems (e.g., FreeBSD, Solaris, etc.)
.. note:: gevent does *not* run on PyPy on Windows because the CFFI backend
does not build.
.. note:: On Windows, gevent is limited to a maximum of 1024 open
sockets due to `limitations in libev`_.
gevent and greenlet can both be installed with `pip`_, e.g., ``pip
install gevent``. On Windows, OS X, and Linux, both gevent and greenlet are
distributed as binary `wheels`_, so no C compiler is required (so long
as pip is at least version 8.0). For other platforms
without pre-built wheels or if wheel installation is disabled, a C compiler
(Xcode on OS X) and the Python development package are required.
`cffi`_ can optionally be installed to build the CFFI backend in
addition to the Cython backend on CPython.
Development instructions (including building from a source checkout)
can be found `on PyPI `_.
__ http://pypi.python.org/pypi/greenlet
.. _`pip`: https://pip.pypa.io/en/stable/installing/
.. _`wheels`: http://pythonwheels.com
.. _`gevent 1.2`: whatsnew_1_2.html
.. _`cffi`: https://cffi.readthedocs.io
.. _`limitations in libev`: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#WIN32_PLATFORM_LIMITATIONS_AND_WORKA
Common Installation Issues
--------------------------
The following are some common installation problems and solutions for
those compiling gevent from source.
- Some Linux distributions are now mounting their temporary
directories with the ``noexec`` option. This can cause a
standard ``pip install gevent`` to fail with an error like
``cannot run C compiled programs``. One fix is to mount the
temporary directory without that option. Another may be to
use the ``--build`` option to ``pip install`` to specify
another directory. See :issue:`570` and :issue:`612` for
examples.
- Also check for conflicts with environment variables like ``CFLAGS``. For
example, see :ref:`library_updates_label`.
- Users of a recent SmartOS release may need to customize
the ``CPPFLAGS`` (the environment variable containing the
default options for the C preprocessor) if they are using the
libev shipped with gevent. See :ref:`operating_systems_label` for
more information.
Example
=======
The following example shows how to run tasks concurrently.
>>> import gevent
>>> from gevent import socket
>>> urls = ['www.google.com', 'www.example.com', 'www.python.org']
>>> jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]
>>> gevent.joinall(jobs, timeout=2)
>>> [job.value for job in jobs]
['74.125.79.106', '208.77.188.166', '82.94.164.162']
After the jobs have been spawned, :func:`gevent.joinall` waits for
them to complete, allowing up to 2 seconds. The results are
then collected by checking the :attr:`~gevent.Greenlet.value` property.
The :func:`gevent.socket.gethostbyname` function has the same
interface as the standard :func:`socket.gethostbyname` but it does not
block the whole interpreter and thus lets the other greenlets proceed
with their requests unhindered.
.. _monkey-patching:
Monkey patching
===============
The example above used :mod:`gevent.socket` for socket operations. If the standard :mod:`socket`
module was used the example would have taken 3 times longer to complete because the DNS requests would
be sequential (serialized). Using the standard socket module inside greenlets makes gevent rather
pointless, so what about existing modules and packages that are built
on top of :mod:`socket` (including the standard library modules like :mod:`urllib`)?
That's where monkey patching comes in. The functions in :mod:`gevent.monkey` carefully
replace functions and classes in the standard :mod:`socket` module with their cooperative
counterparts. That way even the modules that are unaware of gevent can benefit from running
in a multi-greenlet environment.
>>> from gevent import monkey; monkey.patch_socket()
>>> import urllib2 # it's usable from multiple greenlets now
See `examples/concurrent_download.py`__
Beyond sockets
--------------
Of course, there are several other parts of the standard library that can
block the whole interpreter and result in serialized behavior. gevent
provides cooperative versions of many of those as well. They can be
patched independently through individual functions, but most programs
using monkey patching will want to patch the entire recommended set of
modules using the :func:`gevent.monkey.patch_all` function::
>>> from gevent import monkey; monkey.patch_all()
>>> import subprocess # it's usable from multiple greenlets now
.. tip::
When monkey patching, it is recommended to do so as early as
possible in the lifetime of the process. If possible,
monkey patching should be the first lines executed. Monkey
patching later, especially if native threads have been
created, :mod:`atexit` or signal handlers have been installed,
or sockets have been created, may lead to unpredictable
results including unexpected :exc:`~gevent.hub.LoopExit` errors.
__ https://github.com/gevent/gevent/blob/master/examples/concurrent_download.py#L1
Event loop
==========
Instead of blocking and waiting for socket operations to complete (a
technique known as polling), gevent arranges for the operating system
to deliver an event letting it know when, for example, data has
arrived to be read from the socket. Having done that, gevent can move
on to running another greenlet, perhaps one that itself now has an
event ready for it. This repeated process of registering for events
and reacting to them as they arrive is the event loop.
Unlike other network libraries, though in a similar fashion as
eventlet, gevent starts the event loop implicitly in a dedicated
greenlet. There's no ``reactor`` that you must call a ``run()`` or
``dispatch()`` function on. When a function from gevent's API wants to
block, it obtains the :class:`gevent.hub.Hub` instance --- a special
greenlet that runs the event loop --- and switches to it (it is said
that the greenlet *yielded* control to the Hub). If there's no
:class:`~gevent.hub.Hub` instance yet, one is automatically created.
.. tip:: Each operating system thread has its own
:class:`~gevent.hub.Hub`. This makes it possible to use the
gevent blocking API from multiple threads (with care).
The event loop provided by libev uses the fastest polling mechanism
available on the system by default. Please read the `libev documentation`_ for more
information.
.. As of 1.1 or before, we set the EVFLAG_NOENV so this isn't possible any more.
It is possible to command libev to
use a particular polling mechanism by setting the ``LIBEV_FLAGS``
environment variable. Possible values include ``LIBEV_FLAGS=1`` for
the select backend, ``LIBEV_FLAGS=2`` for the poll backend,
``LIBEV_FLAGS=4`` for the epoll backend and ``LIBEV_FLAGS=8`` for the
kqueue backend.
.. _`libev documentation`: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#FUNCTIONS_CONTROLLING_EVENT_LOOPS
The Libev API is available under the :mod:`gevent.core` module. Note that
the callbacks supplied to the libev API are run in the :class:`~gevent.hub.Hub`
greenlet and thus cannot use the synchronous gevent API. It is possible to
use the asynchronous API there, like :func:`gevent.spawn` and
:meth:`gevent.event.Event.set`.
Cooperative multitasking
========================
.. currentmodule:: gevent
The greenlets all run in the same OS thread and are scheduled
cooperatively. This means that until a particular greenlet gives up
control, (by calling a blocking function that will switch to the
:class:`~gevent.hub.Hub`), other greenlets won't get a chance to run. This is
typically not an issue for an I/O bound app, but one should be aware
of this when doing something CPU intensive, or when calling blocking
I/O functions that bypass the libev event loop.
.. tip:: Even some apparently cooperative functions, like
:func:`gevent.sleep`, can temporarily take priority over
waiting I/O operations in some circumstances.
Synchronizing access to objects shared across the greenlets is
unnecessary in most cases (because yielding control is usually
explict), thus traditional synchronization devices like the
:class:`~lock.BoundedSemaphore`, :class:`~lock.RLock` and
:class:`~lock.Semaphore` classes, although present, aren't used very
often. Other abstractions from threading and multiprocessing remain
useful in the cooperative world:
- :class:`~event.Event` allows one to wake up a number of greenlets that are calling :meth:`~event.Event.wait` method.
- :class:`~event.AsyncResult` is similar to :class:`~event.Event` but allows passing a value or an exception to the waiters.
- :class:`~queue.Queue` and :class:`~queue.JoinableQueue`.
Lightweight pseudothreads
=========================
.. currentmodule:: gevent.greenlet
New greenlets are spawned by creating a :class:`~gevent.Greenlet` instance and calling its :meth:`start `
method. (The :func:`gevent.spawn` function is a shortcut that does exactly that). The :meth:`start `
method schedules a switch to the greenlet that will happen as soon as the current greenlet gives up control.
If there is more than one active greenlet, they will be executed one
by one, in an undefined order as they each give up control to the :class:`~gevent.hub.Hub`.
If there is an error during execution it won't escape the greenlet's boundaries. An unhandled error results
in a stacktrace being printed, annotated by the failed function's signature and arguments:
>>> gevent.spawn(lambda : 1/0)
>>> gevent.sleep(1)
Traceback (most recent call last):
...
ZeroDivisionError: integer division or modulo by zero
> failed with ZeroDivisionError
The traceback is asynchronously printed to ``sys.stderr`` when the greenlet dies.
:class:`Greenlet` instances have a number of useful methods:
- :meth:`join ` -- waits until the greenlet exits;
- :meth:`kill ` -- interrupts greenlet's execution;
- :meth:`get ` -- returns the value returned by greenlet or re-raises the exception that killed it.
It is possible to customize the string printed after the traceback by subclassing the :class:`~gevent.Greenlet` class
and redefining its ``__str__`` method.
To subclass a :class:`gevent.Greenlet`, override its
:meth:`gevent.Greenlet._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 synchronously from another greenlet. Killing will resume the sleeping greenlet, but instead
of continuing execution, a :exc:`~gevent.greenlet.GreenletExit` will be raised.
>>> g = MyNoopGreenlet(4)
>>> g.start()
>>> g.kill()
>>> g.dead
True
The :exc:`gevent.greenlet.GreenletExit` exception and its subclasses are handled differently than other exceptions.
Raising :exc:`~gevent.greenlet.GreenletExit` is not considered an exceptional situation, so the traceback is not printed.
The :exc:`~gevent.greenlet.GreenletExit` is returned by :meth:`get ` as if it were returned by the greenlet, not raised.
The :meth:`kill ` method can accept a custom exception to be raised:
>>> 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 ` can also accept a *timeout*
argument specifying the number of seconds to wait for the greenlet to
exit. Note that :meth:`kill ` cannot guarantee
that the target greenlet will not ignore the exception (i.e., it might
catch it), thus it's a good idea always to pass a timeout to
:meth:`kill ` (otherwise, the greenlet doing the
killing will remain blocked forever).
.. tip:: The exact timing at which an exception is raised within a
target greenlet as the result of :meth:`kill
` is not defined. See that function's
documentation for more details.
.. caution:: Use care when killing greenlets, especially arbitrary
greenlets spawned by a library or otherwise executing
code you are not familiar with. If the code being
executed is not prepared to deal with exceptions, object
state may be corrupted. For example, if it has acquired a
``Lock`` but *does not* use a ``finally`` block to
release it, killing the greenlet at the wrong time could
result in the lock being permanently locked::
def func():
# DON'T DO THIS
lock.acquire()
socket.sendall(data) # This could raise many exceptions, including GreenletExit
lock.release()
`This document
`_
describes a similar situation for threads.
Timeouts
========
Many functions in the gevent API are synchronous, blocking the current
greenlet until the operation is done. For example, :meth:`kill
` waits until the target greenlet is
:attr:`~gevent.greenlet.Greenlet.dead` before returning [#f1]_. Many of
those functions can be made asynchronous by passing the keyword argument
``block=False``.
Furthermore, many of the synchronous functions accept a *timeout*
argument, which specifies a limit on how long the function can block
(examples include :meth:`gevent.event.Event.wait`,
:meth:`gevent.Greenlet.join`, :meth:`gevent.Greenlet.kill`,
:meth:`gevent.event.AsyncResult.get`, and many more).
The :class:`socket ` and :class:`SSLObject
` instances can also have a timeout, set by the
:meth:`settimeout ` method.
When these are not enough, the :class:`~gevent.timeout.Timeout` class can be used to
add timeouts to arbitrary sections of (cooperative, yielding) code.
Futher reading
==============
To limit concurrency, use the :class:`gevent.pool.Pool` class (see `example: dns_mass_resolve.py`_).
Gevent comes with TCP/SSL/HTTP/WSGI servers. See :doc:`servers`.
.. _`example: dns_mass_resolve.py`: https://github.com/gevent/gevent/blob/master/examples/dns_mass_resolve.py#L17
External resources
==================
`Gevent for working Python developer`__ is a comprehensive tutorial.
__ http://sdiehl.github.io/gevent-tutorial/
.. rubric:: Footnotes
.. [#f1] This was not the case before 0.13.0, :meth:`kill ` method in 0.12.2 and older was asynchronous by default.
gevent-1.2.2/doc/lowlevel.rst 0000664 0000000 0000000 00000000147 13115240175 0016135 0 ustar 00root root 0000000 0000000 ===================
Low-level details
===================
.. toctree::
gevent.hub
gevent.core
gevent-1.2.2/doc/make.bat 0000664 0000000 0000000 00000005777 13115240175 0015175 0 ustar 00root root 0000000 0000000 @ECHO OFF
REM Command file for Sphinx documentation
set SPHINXBUILD=sphinx-build
set BUILDDIR=_build
set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
if NOT "%PAPER%" == "" (
set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
)
if "%1" == "" goto help
if "%1" == "help" (
:help
echo.Please use `make ^` where ^ is one of
echo. html to make standalone HTML files
echo. dirhtml to make HTML files named index.html in directories
echo. pickle to make pickle files
echo. json to make JSON files
echo. htmlhelp to make HTML files and a HTML help project
echo. qthelp to make HTML files and a qthelp project
echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
echo. changes to make an overview over all changed/added/deprecated items
echo. linkcheck to check all external links for integrity
echo. doctest to run all doctests embedded in the documentation if enabled
goto end
)
if "%1" == "clean" (
for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
del /q /s %BUILDDIR%\*
goto end
)
if "%1" == "html" (
%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/html.
goto end
)
if "%1" == "dirhtml" (
%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
echo.
echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
goto end
)
if "%1" == "pickle" (
%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
echo.
echo.Build finished; now you can process the pickle files.
goto end
)
if "%1" == "json" (
%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
echo.
echo.Build finished; now you can process the JSON files.
goto end
)
if "%1" == "htmlhelp" (
%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
echo.
echo.Build finished; now you can run HTML Help Workshop with the ^
.hhp project file in %BUILDDIR%/htmlhelp.
goto end
)
if "%1" == "qthelp" (
%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
echo.
echo.Build finished; now you can run "qcollectiongenerator" with the ^
.qhcp project file in %BUILDDIR%/qthelp, like this:
echo.^> qcollectiongenerator %BUILDDIR%\qthelp\gevent.qhcp
echo.To view the help file:
echo.^> assistant -collectionFile %BUILDDIR%\qthelp\gevent.ghc
goto end
)
if "%1" == "latex" (
%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
echo.
echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
goto end
)
if "%1" == "changes" (
%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
echo.
echo.The overview file is in %BUILDDIR%/changes.
goto end
)
if "%1" == "linkcheck" (
%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
echo.
echo.Link check complete; look for any errors in the above output ^
or in %BUILDDIR%/linkcheck/output.txt.
goto end
)
if "%1" == "doctest" (
%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
echo.
echo.Testing of doctests in the sources finished, look at the ^
results in %BUILDDIR%/doctest/output.txt.
goto end
)
:end
gevent-1.2.2/doc/mysphinxext.py 0000664 0000000 0000000 00000005207 13115240175 0016526 0 ustar 00root root 0000000 0000000 from __future__ import print_function
from sphinx.ext.autodoc import cut_lines
from sphinx.ext import intersphinx
from docutils import nodes
noisy = 0
message_cache = set()
def missing_reference(app, env, node, contnode):
"""Search the index for missing references.
For example, resolve :class:`Event` to :class:`Event `"""
# XXX methods and functions resolved by this function miss their ()
if intersphinx.missing_reference(app, env, node, contnode) is not None:
# is there a better way to give intersphinx a bigger priority?
return
env = app.builder.env
type = node['reftype']
target = node['reftarget']
modname = node.get('py:module')
classname = node.get('py:class')
if modname and classname:
return
def new_reference(refuri, reftitle):
newnode = nodes.reference('', '')
newnode['refuri'] = refuri
newnode['reftitle'] = reftitle
newnode['py:class'] = 'external-xref'
newnode['classname'] = 'external-xref'
newnode.append(contnode)
msg = 'Resolved missing-reference: :%5s:`%s` -> %s' % (type, target, refuri)
if noisy >= 1 or msg not in message_cache:
print(msg)
message_cache.add(msg)
return newnode
if noisy >= 1:
print('Looking for %s' % [type, target, modname, classname])
print(node)
for docname, items in env.indexentries.items():
if noisy >= 2:
print(docname)
for _x in items:
if noisy >= 4:
print(_x)
(i_type, i_string, i_target, i_aliasname) = _x[:4]
if noisy >= 3:
print('---', [i_type, i_string, i_target, i_aliasname])
if i_aliasname.endswith(target):
stripped_aliasname = i_aliasname[len(docname):]
if stripped_aliasname:
assert stripped_aliasname[0] == '.', repr(stripped_aliasname)
stripped_aliasname = stripped_aliasname[1:]
if stripped_aliasname == target:
if noisy >= 1:
print('--- found %s %s in %s' % (type, target, i_aliasname))
return new_reference(docname + '.html#' + i_aliasname, i_aliasname)
if type == 'mod':
modules = [x for x in env.indexentries.keys() if x.startswith('gevent.')]
target = 'gevent.' + target
if target in modules:
return new_reference(target + '.html', target)
def setup(app):
app.connect('missing-reference', missing_reference)
app.connect('autodoc-process-docstring', cut_lines(2, what=['module']))
gevent-1.2.2/doc/mytheme/ 0000775 0000000 0000000 00000000000 13115240175 0015220 5 ustar 00root root 0000000 0000000 gevent-1.2.2/doc/mytheme/changes/ 0000775 0000000 0000000 00000000000 13115240175 0016630 5 ustar 00root root 0000000 0000000 gevent-1.2.2/doc/mytheme/changes/frameset.html 0000664 0000000 0000000 00000000624 13115240175 0021326 0 ustar 00root root 0000000 0000000
{% trans version=version|e, docstitle=docstitle|e %}Changes in Version {{ version }} — {{ docstitle }}{% endtrans %}
gevent-1.2.2/doc/mytheme/changes/rstsource.html 0000664 0000000 0000000 00000000647 13115240175 0021556 0 ustar 00root root 0000000 0000000
{% trans filename=filename, docstitle=docstitle|e %}{{ filename }} — {{ docstitle }}{% endtrans %}
{% trans %}Please activate JavaScript to enable the search
functionality.{% endtrans %}
{% trans %}From here you can search these documents. Enter your search
words into the box below and click "search". Note that the search
function will automatically search for all of the words. Pages
containing fewer words won't appear in the result list.{% endtrans %}
{% if search_performed %}
{{ _('Search Results') }}
{% if not search_results %}
{{ _('Your search did not match any results.') }}
{% endif %}
{% endif %}
{% if search_results %}
{% for href, caption, context in search_results %}