code
stringlengths 66
870k
| docstring
stringlengths 19
26.7k
| func_name
stringlengths 1
138
| language
stringclasses 1
value | repo
stringlengths 7
68
| path
stringlengths 5
324
| url
stringlengths 46
389
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
def strxor_c(term, c):
"""Return term xored with a sequence of characters c."""
expect_byte_string(term)
if not 0 <= c < 256:
raise ValueError("c must be in range(256)")
result = create_string_buffer(len(term))
_raw_strxor.strxor_c(term, c, result, c_size_t(len(term)))
return get_raw_buffer(result)
|
Return term xored with a sequence of characters c.
|
strxor_c
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Util/strxor.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/strxor.py
|
MIT
|
def pycryptodome_filename(dir_comps, filename):
"""Return the complete file name for the module
dir_comps : list of string
The list of directory names in the PyCryptodome package.
The first element must be "Cryptodome".
filename : string
The filename (inclusing extension) in the target directory.
"""
if dir_comps[0] != "Cryptodome":
raise ValueError("Only available for modules under 'Cryptodome'")
dir_comps = list(dir_comps[1:]) + [filename]
util_lib, _ = os.path.split(os.path.abspath(__file__))
root_lib = os.path.join(util_lib, "..")
return os.path.join(root_lib, *dir_comps)
|
Return the complete file name for the module
dir_comps : list of string
The list of directory names in the PyCryptodome package.
The first element must be "Cryptodome".
filename : string
The filename (inclusing extension) in the target directory.
|
pycryptodome_filename
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Util/_file_system.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/_file_system.py
|
MIT
|
def ceil_shift(n, b):
"""Return ceil(n / 2**b) without performing any floating-point or division operations.
This is done by right-shifting n by b bits and incrementing the result by 1
if any '1' bits were shifted out.
"""
if not isinstance(n, (int, long)) or not isinstance(b, (int, long)):
raise TypeError("unsupported operand type(s): %r and %r" % (type(n).__name__, type(b).__name__))
assert n >= 0 and b >= 0 # I haven't tested or even thought about negative values
mask = (1 << b) - 1
if n & mask:
return (n >> b) + 1
else:
return n >> b
|
Return ceil(n / 2**b) without performing any floating-point or division operations.
This is done by right-shifting n by b bits and incrementing the result by 1
if any '1' bits were shifted out.
|
ceil_shift
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Util/_number_new.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/_number_new.py
|
MIT
|
def ceil_div(a, b):
"""Return ceil(a / b) without performing any floating-point operations."""
if not isinstance(a, (int, long)) or not isinstance(b, (int, long)):
raise TypeError("unsupported operand type(s): %r and %r" % (type(a).__name__, type(b).__name__))
(q, r) = divmod(a, b)
if r:
return q + 1
else:
return q
|
Return ceil(a / b) without performing any floating-point operations.
|
ceil_div
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Util/_number_new.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/_number_new.py
|
MIT
|
def exact_log2(num):
"""Find and return an integer i >= 0 such that num == 2**i.
If no such integer exists, this function raises ValueError.
"""
if not isinstance(num, (int, long)):
raise TypeError("unsupported operand type: %r" % (type(num).__name__,))
n = long(num)
if n <= 0:
raise ValueError("cannot compute logarithm of non-positive number")
i = 0
while n != 0:
if (n & 1) and n != 1:
raise ValueError("No solution could be found")
i += 1
n >>= 1
i -= 1
assert num == (1 << i)
return i
|
Find and return an integer i >= 0 such that num == 2**i.
If no such integer exists, this function raises ValueError.
|
exact_log2
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Util/_number_new.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/_number_new.py
|
MIT
|
def exact_div(p, d, allow_divzero=False):
"""Find and return an integer n such that p == n * d
If no such integer exists, this function raises ValueError.
Both operands must be integers.
If the second operand is zero, this function will raise ZeroDivisionError
unless allow_divzero is true (default: False).
"""
if not isinstance(p, (int, long)) or not isinstance(d, (int, long)):
raise TypeError("unsupported operand type(s): %r and %r" % (type(p).__name__, type(d).__name__))
if d == 0 and allow_divzero:
n = 0
if p != n * d:
raise ValueError("No solution could be found")
else:
(n, r) = divmod(p, d)
if r != 0:
raise ValueError("No solution could be found")
assert p == n * d
return n
|
Find and return an integer n such that p == n * d
If no such integer exists, this function raises ValueError.
Both operands must be integers.
If the second operand is zero, this function will raise ZeroDivisionError
unless allow_divzero is true (default: False).
|
exact_div
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Util/_number_new.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/_number_new.py
|
MIT
|
def load_lib(name, cdecl):
"""Load a shared library and return a handle to it.
@name, either an absolute path or the name of a library
in the system search path.
@cdecl, the C function declarations.
"""
lib = ffi.dlopen(name)
ffi.cdef(cdecl)
return lib
|
Load a shared library and return a handle to it.
@name, either an absolute path or the name of a library
in the system search path.
@cdecl, the C function declarations.
|
load_lib
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Util/_raw_api.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/_raw_api.py
|
MIT
|
def load_pycryptodome_raw_lib(name, cdecl):
"""Load a shared library and return a handle to it.
@name, the name of the library expressed as a PyCryptodome module,
for instance Cryptodome.Cipher._raw_cbc.
@cdecl, the C function declarations.
"""
split = name.split(".")
dir_comps, basename = split[:-1], split[-1]
for ext, mod, typ in imp.get_suffixes():
if typ == imp.C_EXTENSION:
try:
return load_lib(pycryptodome_filename(dir_comps, basename + ext), cdecl)
except OSError:
pass
raise OSError("Cannot load native module '%s'" % name)
|
Load a shared library and return a handle to it.
@name, the name of the library expressed as a PyCryptodome module,
for instance Cryptodome.Cipher._raw_cbc.
@cdecl, the C function declarations.
|
load_pycryptodome_raw_lib
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/Cryptodome/Util/_raw_api.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/Cryptodome/Util/_raw_api.py
|
MIT
|
def __init__(self, listener, locals=None, banner=None, **server_args):
"""
:keyword locals: If given, a dictionary of "builtin" values that will be available
at the top-level.
:keyword banner: If geven, a string that will be printed to each connecting user.
"""
StreamServer.__init__(self, listener, spawn=_Greenlet_stdreplace.spawn, **server_args)
_locals = {'__doc__': None, '__name__': '__console__'}
if locals:
_locals.update(locals)
self.locals = _locals
self.banner = banner
self.stderr = sys.stderr
|
:keyword locals: If given, a dictionary of "builtin" values that will be available
at the top-level.
:keyword banner: If geven, a string that will be printed to each connecting user.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/backdoor.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/backdoor.py
|
MIT
|
def handle(self, conn, address):
"""
Interact with one remote user.
.. versionchanged:: 1.1b2 Each connection gets its own
``locals`` dictionary. Previously they were shared in a
potentially unsafe manner.
"""
fobj = conn.makefile(mode="rw")
fobj = _fileobject(conn, fobj, self.stderr)
getcurrent()._fileobj = fobj
getcurrent().switch_in()
try:
console = InteractiveConsole(self._create_interactive_locals())
console.interact(banner=self.banner)
except SystemExit: # raised by quit()
if hasattr(sys, 'exc_clear'): # py2
sys.exc_clear()
finally:
conn.close()
fobj.close()
|
Interact with one remote user.
.. versionchanged:: 1.1b2 Each connection gets its own
``locals`` dictionary. Previously they were shared in a
potentially unsafe manner.
|
handle
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/backdoor.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/backdoor.py
|
MIT
|
def start(self):
"""Start accepting the connections.
If an address was provided in the constructor, then also create a socket,
bind it and put it into the listening mode.
"""
self.init_socket()
self._stop_event.clear()
try:
self.start_accepting()
except:
self.close()
raise
|
Start accepting the connections.
If an address was provided in the constructor, then also create a socket,
bind it and put it into the listening mode.
|
start
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/baseserver.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/baseserver.py
|
MIT
|
def close(self):
"""Close the listener socket and stop accepting."""
self._stop_event.set()
try:
self.stop_accepting()
finally:
try:
self.socket.close()
except Exception:
pass
finally:
self.__dict__.pop('socket', None)
self.__dict__.pop('handle', None)
self.__dict__.pop('_handle', None)
self.__dict__.pop('_spawn', None)
self.__dict__.pop('full', None)
if self.pool is not None:
self.pool._semaphore.unlink(self._start_accepting_if_started)
|
Close the listener socket and stop accepting.
|
close
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/baseserver.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/baseserver.py
|
MIT
|
def stop(self, timeout=None):
"""
Stop accepting the connections and close the listening socket.
If the server uses a pool to spawn the requests, then
:meth:`stop` also waits for all the handlers to exit. If there
are still handlers executing after *timeout* has expired
(default 1 second, :attr:`stop_timeout`), then the currently
running handlers in the pool are killed.
If the server does not use a pool, then this merely stops accepting connections;
any spawned greenlets that are handling requests continue running until
they naturally complete.
"""
self.close()
if timeout is None:
timeout = self.stop_timeout
if self.pool:
self.pool.join(timeout=timeout)
self.pool.kill(block=True, timeout=1)
|
Stop accepting the connections and close the listening socket.
If the server uses a pool to spawn the requests, then
:meth:`stop` also waits for all the handlers to exit. If there
are still handlers executing after *timeout* has expired
(default 1 second, :attr:`stop_timeout`), then the currently
running handlers in the pool are killed.
If the server does not use a pool, then this merely stops accepting connections;
any spawned greenlets that are handling requests continue running until
they naturally complete.
|
stop
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/baseserver.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/baseserver.py
|
MIT
|
def serve_forever(self, stop_timeout=None):
"""Start the server if it hasn't been already started and wait until it's stopped."""
# add test that serve_forever exists on stop()
if not self.started:
self.start()
try:
self._stop_event.wait()
finally:
Greenlet.spawn(self.stop, timeout=stop_timeout).join()
|
Start the server if it hasn't been already started and wait until it's stopped.
|
serve_forever
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/baseserver.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/baseserver.py
|
MIT
|
def __import__(*args, **kwargs):
"""
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> object
Normally python protects imports against concurrency by doing some locking
at the C level (at least, it does that in CPython). This function just
wraps the normal __import__ functionality in a recursive lock, ensuring that
we're protected against greenlet import concurrency as well.
"""
if len(args) > 0 and not issubclass(type(args[0]), _allowed_module_name_types):
# if a builtin has been acquired as a bound instance method,
# python knows not to pass 'self' when the method is called.
# No such protection exists for monkey-patched builtins,
# however, so this is necessary.
args = args[1:]
if not __lock_imports:
return _import(*args, **kwargs)
module_lock = __module_lock(args[0]) # Get a lock for the module name
imp.acquire_lock()
try:
module_lock.acquire()
try:
result = _import(*args, **kwargs)
finally:
module_lock.release()
finally:
imp.release_lock()
return result
|
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> object
Normally python protects imports against concurrency by doing some locking
at the C level (at least, it does that in CPython). This function just
wraps the normal __import__ functionality in a recursive lock, ensuring that
we're protected against greenlet import concurrency as well.
|
__import__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/builtins.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/builtins.py
|
MIT
|
def _python_callback(handle, revents):
"""
Returns an integer having one of three values:
- -1
An exception occurred during the callback and you must call
:func:`_python_handle_error` to deal with it. The Python watcher
object will have the exception tuple saved in ``_exc_info``.
- 0
Everything went according to plan. You should check to see if the libev
watcher is still active, and call :func:`_python_stop` if so. This will
clean up the memory.
- 1
Everything went according to plan, but the watcher has already
been stopped. Its memory may no longer be valid.
"""
try:
# Even dereferencing the handle needs to be inside the try/except;
# if we don't return normally (e.g., a signal) then we wind up going
# to the 'onerror' handler, which
# is not what we want; that can permanently wedge the loop depending
# on which callback was executing
watcher = ffi.from_handle(handle)
args = watcher.args
if args is None:
# Legacy behaviour from corecext: convert None into ()
# See test__core_watcher.py
args = _NOARGS
if len(args) > 0 and args[0] == GEVENT_CORE_EVENTS:
args = (revents, ) + args[1:]
watcher.callback(*args)
except:
watcher._exc_info = sys.exc_info()
# Depending on when the exception happened, the watcher
# may or may not have been stopped. We need to make sure its
# memory stays valid so we can stop it at the ev level if needed.
watcher.loop._keepaliveset.add(watcher)
return -1
else:
if watcher in watcher.loop._keepaliveset:
# It didn't stop itself
return 0
return 1 # It stopped itself
|
Returns an integer having one of three values:
- -1
An exception occurred during the callback and you must call
:func:`_python_handle_error` to deal with it. The Python watcher
object will have the exception tuple saved in ``_exc_info``.
- 0
Everything went according to plan. You should check to see if the libev
watcher is still active, and call :func:`_python_stop` if so. This will
clean up the memory.
- 1
Everything went according to plan, but the watcher has already
been stopped. Its memory may no longer be valid.
|
_python_callback
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/corecffi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/corecffi.py
|
MIT
|
def rawlink(self, callback):
"""
Register a callback to call when this object is ready.
*callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
*callback* will be passed one argument: this instance.
"""
if not callable(callback):
raise TypeError('Expected callable: %r' % (callback, ))
self._links.add(callback)
self._check_and_notify()
|
Register a callback to call when this object is ready.
*callback* will be called in the :class:`Hub <gevent.hub.Hub>`, so it must not use blocking gevent API.
*callback* will be passed one argument: this instance.
|
rawlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/event.py
|
MIT
|
def unlink(self, callback):
"""Remove the callback set by :meth:`rawlink`"""
try:
self._links.remove(callback)
except KeyError:
pass
|
Remove the callback set by :meth:`rawlink`
|
unlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/event.py
|
MIT
|
def exc_info(self):
"""
The three-tuple of exception information if :meth:`set_exception` was called.
"""
if self._exc_info:
return (self._exc_info[0], self._exc_info[1], load_traceback(self._exc_info[2]))
return ()
|
The three-tuple of exception information if :meth:`set_exception` was called.
|
exc_info
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/event.py
|
MIT
|
def set_exception(self, exception, exc_info=None):
"""Store the exception and wake up any waiters.
All greenlets blocking on :meth:`get` or :meth:`wait` are awakened.
Subsequent calls to :meth:`wait` and :meth:`get` will not block at all.
:keyword tuple exc_info: If given, a standard three-tuple of type, value, :class:`traceback`
as returned by :func:`sys.exc_info`. This will be used when the exception
is re-raised to propagate the correct traceback.
"""
if exc_info:
self._exc_info = (exc_info[0], exc_info[1], dump_traceback(exc_info[2]))
else:
self._exc_info = (type(exception), exception, dump_traceback(None))
self._check_and_notify()
|
Store the exception and wake up any waiters.
All greenlets blocking on :meth:`get` or :meth:`wait` are awakened.
Subsequent calls to :meth:`wait` and :meth:`get` will not block at all.
:keyword tuple exc_info: If given, a standard three-tuple of type, value, :class:`traceback`
as returned by :func:`sys.exc_info`. This will be used when the exception
is re-raised to propagate the correct traceback.
|
set_exception
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/event.py
|
MIT
|
def get(self, block=True, timeout=None):
"""Return the stored value or raise the exception.
If this instance already holds a value or an exception, return or raise it immediatelly.
Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception` or
until the optional timeout occurs.
When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). If the *timeout* elapses, the *Timeout* exception will
be raised.
:keyword bool block: If set to ``False`` and this instance is not ready,
immediately raise a :class:`Timeout` exception.
"""
if self._value is not _NONE:
return self._value
if self._exc_info:
return self._raise_exception()
if not block:
# Not ready and not blocking, so immediately timeout
raise Timeout()
# Wait, raising a timeout that elapses
self._wait_core(timeout, ())
# by definition we are now ready
return self.get(block=False)
|
Return the stored value or raise the exception.
If this instance already holds a value or an exception, return or raise it immediatelly.
Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception` or
until the optional timeout occurs.
When the *timeout* argument is present and not ``None``, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). If the *timeout* elapses, the *Timeout* exception will
be raised.
:keyword bool block: If set to ``False`` and this instance is not ready,
immediately raise a :class:`Timeout` exception.
|
get
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/event.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/event.py
|
MIT
|
def __init__(self, fobj, *args, **kwargs):
"""
:param fobj: The underlying file-like object to wrap, or an integer fileno
that will be pass to :func:`os.fdopen` along with everything in *args*.
:keyword bool lock: If True (the default) then all operations will
be performed one-by-one. Note that this does not guarantee that, if using
this file object from multiple threads/greenlets, operations will be performed
in any particular order, only that no two operations will be attempted at the
same time. You can also pass your own :class:`gevent.lock.Semaphore` to synchronize
file operations with an external resource.
:keyword bool close: If True (the default) then when this object is closed,
the underlying object is closed as well.
"""
self._close = kwargs.pop('close', True)
self.threadpool = kwargs.pop('threadpool', None)
self.lock = kwargs.pop('lock', True)
if kwargs:
raise TypeError('Unexpected arguments: %r' % kwargs.keys())
if self.lock is True:
self.lock = Semaphore()
elif not self.lock:
self.lock = DummySemaphore()
if not hasattr(self.lock, '__enter__'):
raise TypeError('Expected a Semaphore or boolean, got %r' % type(self.lock))
if isinstance(fobj, integer_types):
if not self._close:
# we cannot do this, since fdopen object will close the descriptor
raise TypeError('FileObjectThread does not support close=False')
fobj = os.fdopen(fobj, *args)
self.io = fobj
if self.threadpool is None:
self.threadpool = get_hub().threadpool
|
:param fobj: The underlying file-like object to wrap, or an integer fileno
that will be pass to :func:`os.fdopen` along with everything in *args*.
:keyword bool lock: If True (the default) then all operations will
be performed one-by-one. Note that this does not guarantee that, if using
this file object from multiple threads/greenlets, operations will be performed
in any particular order, only that no two operations will be attempted at the
same time. You can also pass your own :class:`gevent.lock.Semaphore` to synchronize
file operations with an external resource.
:keyword bool close: If True (the default) then when this object is closed,
the underlying object is closed as well.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/fileobject.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/fileobject.py
|
MIT
|
def close(self):
"""
.. versionchanged:: 1.1b1
The file object is closed using the threadpool. Note that whether or
not this action is synchronous or asynchronous is not documented.
"""
fobj = self.io
if fobj is None:
return
self.io = None
try:
self.flush(_fobj=fobj)
finally:
if self._close:
# Note that we're not using self._apply; older code
# did fobj.close() without going through the threadpool at all,
# so acquiring the lock could potentially introduce deadlocks
# that weren't present before. Avoiding the lock doesn't make
# the existing race condition any worse.
# We wrap the close in an exception handler and re-raise directly
# to avoid the (common, expected) IOError from being logged
def close():
try:
fobj.close()
except:
return sys.exc_info()
exc_info = self.threadpool.apply(close)
if exc_info:
reraise(*exc_info)
|
.. versionchanged:: 1.1b1
The file object is closed using the threadpool. Note that whether or
not this action is synchronous or asynchronous is not documented.
|
close
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/fileobject.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/fileobject.py
|
MIT
|
def __init__(self, run=None, *args, **kwargs):
"""
Greenlet constructor.
:param args: The arguments passed to the ``run`` function.
:param kwargs: The keyword arguments passed to the ``run`` function.
:keyword run: The callable object to run. If not given, this object's
`_run` method will be invoked (typically defined by subclasses).
.. versionchanged:: 1.1b1
The ``run`` argument to the constructor is now verified to be a callable
object. Previously, passing a non-callable object would fail after the greenlet
was spawned.
"""
# greenlet.greenlet(run=None, parent=None)
# Calling it with both positional arguments instead of a keyword
# argument (parent=get_hub()) speeds up creation of this object ~30%:
# python -m timeit -s 'import gevent' 'gevent.Greenlet()'
# Python 3.5: 2.70usec with keywords vs 1.94usec with positional
# Python 3.4: 2.32usec with keywords vs 1.74usec with positional
# Python 3.3: 2.55usec with keywords vs 1.92usec with positional
# Python 2.7: 1.73usec with keywords vs 1.40usec with positional
greenlet.__init__(self, None, get_hub())
if run is not None:
self._run = run
# If they didn't pass a callable at all, then they must
# already have one. Note that subclassing to override the run() method
# itself has never been documented or supported.
if not callable(self._run):
raise TypeError("The run argument or self._run must be callable")
if args:
self.args = args
if kwargs:
self._kwargs = kwargs
|
Greenlet constructor.
:param args: The arguments passed to the ``run`` function.
:param kwargs: The keyword arguments passed to the ``run`` function.
:keyword run: The callable object to run. If not given, this object's
`_run` method will be invoked (typically defined by subclasses).
.. versionchanged:: 1.1b1
The ``run`` argument to the constructor is now verified to be a callable
object. Previously, passing a non-callable object would fail after the greenlet
was spawned.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def exc_info(self):
"""Holds the exc_info three-tuple raised by the function if the greenlet finished with an error.
Otherwise a false value."""
e = self._exc_info
if e:
return (e[0], e[1], load_traceback(e[2]))
|
Holds the exc_info three-tuple raised by the function if the greenlet finished with an error.
Otherwise a false value.
|
exc_info
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def throw(self, *args):
"""Immediatelly switch into the greenlet and raise an exception in it.
Should only be called from the HUB, otherwise the current greenlet is left unscheduled forever.
To raise an exception in a safe manner from any greenlet, use :meth:`kill`.
If a greenlet was started but never switched to yet, then also
a) cancel the event that will start it
b) fire the notifications as if an exception was raised in a greenlet
"""
self.__cancel_start()
try:
if not self.dead:
# Prevent switching into a greenlet *at all* if we had never
# started it. Usually this is the same thing that happens by throwing,
# but if this is done from the hub with nothing else running, prevents a
# LoopExit.
greenlet.throw(self, *args)
finally:
self.__handle_death_before_start(*args)
|
Immediatelly switch into the greenlet and raise an exception in it.
Should only be called from the HUB, otherwise the current greenlet is left unscheduled forever.
To raise an exception in a safe manner from any greenlet, use :meth:`kill`.
If a greenlet was started but never switched to yet, then also
a) cancel the event that will start it
b) fire the notifications as if an exception was raised in a greenlet
|
throw
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def start(self):
"""Schedule the greenlet to run in this loop iteration"""
if self._start_event is None:
self._start_event = self.parent.loop.run_callback(self.switch)
|
Schedule the greenlet to run in this loop iteration
|
start
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def start_later(self, seconds):
"""Schedule the greenlet to run in the future loop iteration *seconds* later"""
if self._start_event is None:
self._start_event = self.parent.loop.timer(seconds)
self._start_event.start(self.switch)
|
Schedule the greenlet to run in the future loop iteration *seconds* later
|
start_later
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def spawn(cls, *args, **kwargs):
"""
Create a new :class:`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 :meth:`Greenlet.__init__`.
.. versionchanged:: 1.1b1
If a *function* is given that is not callable, immediately raise a :exc:`TypeError`
instead of spawning a greenlet that will raise an uncaught TypeError.
"""
g = cls(*args, **kwargs)
g.start()
return g
|
Create a new :class:`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 :meth:`Greenlet.__init__`.
.. versionchanged:: 1.1b1
If a *function* is given that is not callable, immediately raise a :exc:`TypeError`
instead of spawning a greenlet that will raise an uncaught TypeError.
|
spawn
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def spawn_later(cls, seconds, *args, **kwargs):
"""
Create and return a new Greenlet object scheduled to run ``function(*args, **kwargs)``
in the future loop iteration *seconds* later. This can be used as ``Greenlet.spawn_later``
or ``gevent.spawn_later``.
The arguments are passed to :meth:`Greenlet.__init__`.
.. versionchanged:: 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.
"""
if cls is Greenlet and not args and 'run' not in kwargs:
raise TypeError("")
g = cls(*args, **kwargs)
g.start_later(seconds)
return g
|
Create and return a new Greenlet object scheduled to run ``function(*args, **kwargs)``
in the future loop iteration *seconds* later. This can be used as ``Greenlet.spawn_later``
or ``gevent.spawn_later``.
The arguments are passed to :meth:`Greenlet.__init__`.
.. versionchanged:: 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_later
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def kill(self, exception=GreenletExit, block=True, timeout=None):
"""
Raise the ``exception`` in the greenlet.
If ``block`` is ``True`` (the default), wait until the greenlet dies or the optional timeout expires.
If block is ``False``, the current greenlet is not unscheduled.
The function always returns ``None`` and never raises an error.
.. 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 :func:`sleep(0)
<gevent.sleep>`; an example where the exception is raised
immediately is if this greenlet had called
:func:`sleep(0.1) <gevent.sleep>`.
See also :func:`gevent.kill`.
:keyword type exception: The type of exception to raise in the greenlet. The default
is :class:`GreenletExit`, which indicates a :meth:`successful` completion
of the greenlet.
.. versionchanged:: 0.13.0
*block* is now ``True`` by default.
.. versionchanged:: 1.1a2
If this greenlet had never been switched to, killing it will prevent it from ever being switched to.
"""
self.__cancel_start()
if self.dead:
self.__handle_death_before_start(exception)
else:
waiter = Waiter() if block else None
self.parent.loop.run_callback(_kill, self, exception, waiter)
if block:
waiter.get()
self.join(timeout)
# it should be OK to use kill() in finally or kill a greenlet from more than one place;
# thus it should not raise when the greenlet is already killed (= not started)
|
Raise the ``exception`` in the greenlet.
If ``block`` is ``True`` (the default), wait until the greenlet dies or the optional timeout expires.
If block is ``False``, the current greenlet is not unscheduled.
The function always returns ``None`` and never raises an error.
.. 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 :func:`sleep(0)
<gevent.sleep>`; an example where the exception is raised
immediately is if this greenlet had called
:func:`sleep(0.1) <gevent.sleep>`.
See also :func:`gevent.kill`.
:keyword type exception: The type of exception to raise in the greenlet. The default
is :class:`GreenletExit`, which indicates a :meth:`successful` completion
of the greenlet.
.. versionchanged:: 0.13.0
*block* is now ``True`` by default.
.. versionchanged:: 1.1a2
If this greenlet had never been switched to, killing it will prevent it from ever being switched to.
|
kill
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def get(self, block=True, timeout=None):
"""Return the result the greenlet has returned or re-raise the exception it has raised.
If block is ``False``, raise :class:`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, :class:`gevent.Timeout` is raised.
"""
if self.ready():
if self.successful():
return self.value
self._raise_exception()
if not block:
raise Timeout()
switch = getcurrent().switch
self.rawlink(switch)
try:
t = Timeout._start_new_or_dummy(timeout)
try:
result = self.parent.switch()
if result is not self:
raise InvalidSwitchError('Invalid switch into Greenlet.get(): %r' % (result, ))
finally:
t.cancel()
except:
# unlinking in 'except' instead of finally is an optimization:
# if switch occurred normally then link was already removed in _notify_links
# and there's no need to touch the links set.
# Note, however, that if "Invalid switch" assert was removed and invalid switch
# did happen, the link would remain, causing another invalid switch later in this greenlet.
self.unlink(switch)
raise
if self.ready():
if self.successful():
return self.value
self._raise_exception()
|
Return the result the greenlet has returned or re-raise the exception it has raised.
If block is ``False``, raise :class:`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, :class:`gevent.Timeout` is raised.
|
get
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def join(self, timeout=None):
"""Wait until the greenlet finishes or *timeout* expires.
Return ``None`` regardless.
"""
if self.ready():
return
switch = getcurrent().switch
self.rawlink(switch)
try:
t = Timeout._start_new_or_dummy(timeout)
try:
result = self.parent.switch()
if result is not self:
raise InvalidSwitchError('Invalid switch into Greenlet.join(): %r' % (result, ))
finally:
t.cancel()
except Timeout as ex:
self.unlink(switch)
if ex is not t:
raise
except:
self.unlink(switch)
raise
|
Wait until the greenlet finishes or *timeout* expires.
Return ``None`` regardless.
|
join
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def rawlink(self, callback):
"""Register a callable to be executed when the greenlet finishes execution.
The *callback* will be called with this instance as an argument.
.. caution:: The callable will be called in the HUB greenlet.
"""
if not callable(callback):
raise TypeError('Expected callable: %r' % (callback, ))
self._links.append(callback)
if self.ready() and self._links and not self._notifier:
self._notifier = self.parent.loop.run_callback(self._notify_links)
|
Register a callable to be executed when the greenlet finishes execution.
The *callback* will be called with this instance as an argument.
.. caution:: The callable will be called in the HUB greenlet.
|
rawlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def unlink(self, callback):
"""Remove the callback set by :meth:`link` or :meth:`rawlink`"""
try:
self._links.remove(callback)
except ValueError:
pass
|
Remove the callback set by :meth:`link` or :meth:`rawlink`
|
unlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def joinall(greenlets, timeout=None, raise_error=False, count=None):
"""
Wait for the ``greenlets`` to finish.
:param greenlets: A sequence (supporting :func:`len`) of greenlets to wait for.
:keyword float timeout: If given, the maximum number of seconds to wait.
:return: A sequence of the greenlets that finished before the timeout (if any)
expired.
"""
if not raise_error:
return wait(greenlets, timeout=timeout, count=count)
done = []
for obj in iwait(greenlets, timeout=timeout, count=count):
if getattr(obj, 'exception', None) is not None:
if hasattr(obj, '_raise_exception'):
obj._raise_exception()
else:
raise obj.exception
done.append(obj)
return done
|
Wait for the ``greenlets`` to finish.
:param greenlets: A sequence (supporting :func:`len`) of greenlets to wait for.
:keyword float timeout: If given, the maximum number of seconds to wait.
:return: A sequence of the greenlets that finished before the timeout (if any)
expired.
|
joinall
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def killall(greenlets, exception=GreenletExit, block=True, timeout=None):
"""
Forceably terminate all the ``greenlets`` by causing them to raise ``exception``.
:param 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.
:keyword exception: The exception to raise in the greenlets. By default this is
:class:`GreenletExit`.
:keyword bool block: 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 :func:`gevent.joinall`) and allowed to die naturally.
If False, this function returns immediately and greenlets will raise
the exception asynchronously.
:keyword float timeout: A time in seconds to wait for greenlets to die. If given, it is
only honored when ``block`` is True.
:raise Timeout: If blocking and a timeout is given that elapses before
all the greenlets are dead.
.. versionchanged:: 1.1a2
*greenlets* can be any iterable of greenlets, like an iterator or a set.
Previously it had to be a list or tuple.
"""
# support non-indexable containers like iterators or set objects
greenlets = list(greenlets)
if not greenlets:
return
loop = greenlets[0].loop
if block:
waiter = Waiter()
loop.run_callback(_killall3, greenlets, exception, waiter)
t = Timeout._start_new_or_dummy(timeout)
try:
alive = waiter.get()
if alive:
joinall(alive, raise_error=False)
finally:
t.cancel()
else:
loop.run_callback(_killall, greenlets, exception)
|
Forceably terminate all the ``greenlets`` by causing them to raise ``exception``.
:param 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.
:keyword exception: The exception to raise in the greenlets. By default this is
:class:`GreenletExit`.
:keyword bool block: 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 :func:`gevent.joinall`) and allowed to die naturally.
If False, this function returns immediately and greenlets will raise
the exception asynchronously.
:keyword float timeout: A time in seconds to wait for greenlets to die. If given, it is
only honored when ``block`` is True.
:raise Timeout: If blocking and a timeout is given that elapses before
all the greenlets are dead.
.. versionchanged:: 1.1a2
*greenlets* can be any iterable of greenlets, like an iterator or a set.
Previously it had to be a list or tuple.
|
killall
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/greenlet.py
|
MIT
|
def spawn_raw(function, *args, **kwargs):
"""
Create a new :class:`greenlet.greenlet` object and schedule it to
run ``function(*args, **kwargs)``.
This returns a raw :class:`~greenlet.greenlet` which does not have all the useful
methods that :class:`gevent.Greenlet` has. Typically, applications
should prefer :func:`~gevent.spawn`, but this method may
occasionally be useful as an optimization if there are many
greenlets involved.
.. versionchanged:: 1.1b1
If *function* is not callable, immediately raise a :exc:`TypeError`
instead of spawning a greenlet that will raise an uncaught TypeError.
.. versionchanged:: 1.1rc2
Accept keyword arguments for ``function`` as previously (incorrectly)
documented. Note that this may incur an additional expense.
.. versionchanged:: 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.
"""
if not callable(function):
raise TypeError("function must be callable")
hub = get_hub()
# The callback class object that we use to run this doesn't
# accept kwargs (and those objects are heavily used, as well as being
# implemented twice in core.ppyx and corecffi.py) so do it with a partial
if kwargs:
function = _functools_partial(function, *args, **kwargs)
g = greenlet(function, hub)
hub.loop.run_callback(g.switch)
else:
g = greenlet(function, hub)
hub.loop.run_callback(g.switch, *args)
return g
|
Create a new :class:`greenlet.greenlet` object and schedule it to
run ``function(*args, **kwargs)``.
This returns a raw :class:`~greenlet.greenlet` which does not have all the useful
methods that :class:`gevent.Greenlet` has. Typically, applications
should prefer :func:`~gevent.spawn`, but this method may
occasionally be useful as an optimization if there are many
greenlets involved.
.. versionchanged:: 1.1b1
If *function* is not callable, immediately raise a :exc:`TypeError`
instead of spawning a greenlet that will raise an uncaught TypeError.
.. versionchanged:: 1.1rc2
Accept keyword arguments for ``function`` as previously (incorrectly)
documented. Note that this may incur an additional expense.
.. versionchanged:: 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.
|
spawn_raw
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def sleep(seconds=0, ref=True):
"""
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 :func:`gevent.wait`
from exiting.
.. seealso:: :func:`idle`
"""
hub = get_hub()
loop = hub.loop
if seconds <= 0:
waiter = Waiter()
loop.run_callback(waiter.switch)
waiter.get()
else:
hub.wait(loop.timer(seconds, ref=ref))
|
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 :func:`gevent.wait`
from exiting.
.. seealso:: :func:`idle`
|
sleep
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def idle(priority=0):
"""
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.
.. seealso:: :func:`sleep`
"""
hub = get_hub()
watcher = hub.loop.idle()
if priority:
watcher.priority = priority
hub.wait(watcher)
|
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.
.. seealso:: :func:`sleep`
|
idle
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def kill(greenlet, exception=GreenletExit):
"""
Kill greenlet asynchronously. The current greenlet is not unscheduled.
.. note::
The method :meth:`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 :func:`spawn_raw`,
so you have to use this function.
.. versionchanged:: 1.1a2
If the ``greenlet`` has a :meth:`kill <Greenlet.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.
"""
if not greenlet.dead:
if hasattr(greenlet, 'kill'):
# dealing with gevent.greenlet.Greenlet. Use it, especially
# to avoid allowing one to be switched to for the first time
# after it's been killed
greenlet.kill(exception=exception, block=False)
else:
get_hub().loop.run_callback(greenlet.throw, exception)
|
Kill greenlet asynchronously. The current greenlet is not unscheduled.
.. note::
The method :meth:`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 :func:`spawn_raw`,
so you have to use this function.
.. versionchanged:: 1.1a2
If the ``greenlet`` has a :meth:`kill <Greenlet.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.
|
kill
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def reinit():
"""
Prepare the gevent hub to run in a new (forked) process.
This should be called *immediately* after :func:`os.fork` in the
child process. This is done automatically by
:func:`gevent.os.fork` or if the :mod:`os` module has been
monkey-patched. If this function is not called in a forked
process, symptoms may include hanging of functions like
:func:`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 :func:`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 :func:`gevent.os.fork` about greenlets
and libev watchers in the child process.
"""
# The loop reinit function in turn calls libev's ev_loop_fork
# function.
hub = _get_hub()
if hub is not None:
# Note that we reinit the existing loop, not destroy it.
# See https://github.com/gevent/gevent/issues/200.
hub.loop.reinit()
# libev's fork watchers are slow to fire because the only fire
# at the beginning of a loop; due to our use of callbacks that
# run at the end of the loop, that may be too late. The
# threadpool and resolvers depend on the fork handlers being
# run (specifically, the threadpool will fail in the forked
# child if there were any threads in it, which there will be
# if the resolver_thread was in use (the default) before the
# fork.)
#
# If the forked process wants to use the threadpool or
# resolver immediately (in a queued callback), it would hang.
#
# The below is a workaround. Fortunately, both of these
# methods are idempotent and can be called multiple times
# following a fork if the suddenly started working, or were
# already working on some platforms. Other threadpools and fork handlers
# will be called at an arbitrary time later ('soon')
if hasattr(hub.threadpool, '_on_fork'):
hub.threadpool._on_fork()
# resolver_ares also has a fork watcher that's not firing
if hasattr(hub.resolver, '_on_fork'):
hub.resolver._on_fork()
# TODO: We'd like to sleep for a non-zero amount of time to force the loop to make a
# pass around before returning to this greenlet. That will allow any
# user-provided fork watchers to run. (Two calls are necessary.) HOWEVER, if
# we do this, certain tests that heavily mix threads and forking,
# like 2.7/test_threading:test_reinit_tls_after_fork, fail. It's not immediately clear
# why.
#sleep(0.00001)
#sleep(0.00001)
|
Prepare the gevent hub to run in a new (forked) process.
This should be called *immediately* after :func:`os.fork` in the
child process. This is done automatically by
:func:`gevent.os.fork` or if the :mod:`os` module has been
monkey-patched. If this function is not called in a forked
process, symptoms may include hanging of functions like
:func:`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 :func:`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 :func:`gevent.os.fork` about greenlets
and libev watchers in the child process.
|
reinit
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def get_hub_class():
"""Return the type of hub to use for the current thread.
If there's no type of hub for the current thread yet, 'gevent.hub.Hub' is used.
"""
hubtype = _threadlocal.Hub
if hubtype is None:
hubtype = _threadlocal.Hub = Hub
return hubtype
|
Return the type of hub to use for the current thread.
If there's no type of hub for the current thread yet, 'gevent.hub.Hub' is used.
|
get_hub_class
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def get_hub(*args, **kwargs):
"""
Return the hub for the current thread.
If a hub does not exist in the current thread, a new one is
created of the type returned by :func:`get_hub_class`.
"""
hub = _threadlocal.hub
if hub is None:
hubtype = get_hub_class()
hub = _threadlocal.hub = hubtype(*args, **kwargs)
return hub
|
Return the hub for the current thread.
If a hub does not exist in the current thread, a new one is
created of the type returned by :func:`get_hub_class`.
|
get_hub
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def handle_error(self, context, type, value, tb):
"""
Called by the event loop when an error occurs. The arguments
type, value, and tb are the standard tuple returned by :func:`sys.exc_info`.
Applications can set a property on the hub with this same signature
to override the error handling provided by this class.
Errors that are :attr:`system errors <SYSTEM_ERROR>` are passed
to :meth:`handle_system_error`.
:param context: If this is ``None``, indicates a system error that
should generally result in exiting the loop and being thrown to the
parent greenlet.
"""
if isinstance(value, str):
# Cython can raise errors where the value is a plain string
# e.g., AttributeError, "_semaphore.Semaphore has no attr", <traceback>
value = type(value)
if not issubclass(type, self.NOT_ERROR):
self.print_exception(context, type, value, tb)
if context is None or issubclass(type, self.SYSTEM_ERROR):
self.handle_system_error(type, value)
|
Called by the event loop when an error occurs. The arguments
type, value, and tb are the standard tuple returned by :func:`sys.exc_info`.
Applications can set a property on the hub with this same signature
to override the error handling provided by this class.
Errors that are :attr:`system errors <SYSTEM_ERROR>` are passed
to :meth:`handle_system_error`.
:param context: If this is ``None``, indicates a system error that
should generally result in exiting the loop and being thrown to the
parent greenlet.
|
handle_error
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def wait(self, watcher):
"""
Wait until the *watcher* (which should not be started) is ready.
The current greenlet will be unscheduled during this time.
.. seealso:: :class:`gevent.core.io`, :class:`gevent.core.timer`,
:class:`gevent.core.signal`, :class:`gevent.core.idle`, :class:`gevent.core.prepare`,
:class:`gevent.core.check`, :class:`gevent.core.fork`, :class:`gevent.core.async`,
:class:`gevent.core.child`, :class:`gevent.core.stat`
"""
waiter = Waiter()
unique = object()
watcher.start(waiter.switch, unique)
try:
result = waiter.get()
if result is not unique:
raise InvalidSwitchError('Invalid switch into %s: %r (expected %r)' % (getcurrent(), result, unique))
finally:
watcher.stop()
|
Wait until the *watcher* (which should not be started) is ready.
The current greenlet will be unscheduled during this time.
.. seealso:: :class:`gevent.core.io`, :class:`gevent.core.timer`,
:class:`gevent.core.signal`, :class:`gevent.core.idle`, :class:`gevent.core.prepare`,
:class:`gevent.core.check`, :class:`gevent.core.fork`, :class:`gevent.core.async`,
:class:`gevent.core.child`, :class:`gevent.core.stat`
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def cancel_wait(self, watcher, error):
"""
Cancel an in-progress call to :meth:`wait` by throwing the given *error*
in the waiting greenlet.
"""
if watcher.callback is not None:
self.loop.run_callback(self._cancel_wait, watcher, error)
|
Cancel an in-progress call to :meth:`wait` by throwing the given *error*
in the waiting greenlet.
|
cancel_wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def run(self):
"""
Entry-point to running the loop. This method is called automatically
when the hub greenlet is scheduled; do not call it directly.
:raises LoopExit: If the loop finishes running. This means
that there are no other scheduled greenlets, and no active
watchers or servers. In some situations, this indicates a
programming error.
"""
assert self is getcurrent(), 'Do not call Hub.run() directly'
while True:
loop = self.loop
loop.error_handler = self
try:
loop.run()
finally:
loop.error_handler = None # break the refcount cycle
self.parent.throw(LoopExit('This operation would block forever', self))
# this function must never return, as it will cause switch() in the parent greenlet
# to return an unexpected value
# It is still possible to kill this greenlet with throw. However, in that case
# switching to it is no longer safe, as switch will return immediatelly
|
Entry-point to running the loop. This method is called automatically
when the hub greenlet is scheduled; do not call it directly.
:raises LoopExit: If the loop finishes running. This means
that there are no other scheduled greenlets, and no active
watchers or servers. In some situations, this indicates a
programming error.
|
run
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def join(self, timeout=None):
"""Wait for the event loop to finish. Exits only when there are
no more spawned greenlets, started servers, active timeouts or watchers.
If *timeout* is provided, wait no longer for the specified number of seconds.
Returns True if exited because the loop finished execution.
Returns False if exited because of timeout expired.
"""
assert getcurrent() is self.parent, "only possible from the MAIN greenlet"
if self.dead:
return True
waiter = Waiter()
if timeout is not None:
timeout = self.loop.timer(timeout, ref=False)
timeout.start(waiter.switch)
try:
try:
waiter.get()
except LoopExit:
return True
finally:
if timeout is not None:
timeout.stop()
return False
|
Wait for the event loop to finish. Exits only when there are
no more spawned greenlets, started servers, active timeouts or watchers.
If *timeout* is provided, wait no longer for the specified number of seconds.
Returns True if exited because the loop finished execution.
Returns False if exited because of timeout expired.
|
join
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def exc_info(self):
"Holds the exception info passed to :meth:`throw` if :meth:`throw` was called. Otherwise ``None``."
if self._exception is not _NONE:
return self._exception
|
Holds the exception info passed to :meth:`throw` if :meth:`throw` was called. Otherwise ``None``.
|
exc_info
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def switch(self, value=None):
"""Switch to the greenlet if one's available. Otherwise store the value."""
greenlet = self.greenlet
if greenlet is None:
self.value = value
self._exception = None
else:
assert getcurrent() is self.hub, "Can only use Waiter.switch method from the Hub greenlet"
switch = greenlet.switch
try:
switch(value)
except:
self.hub.handle_error(switch, *sys.exc_info())
|
Switch to the greenlet if one's available. Otherwise store the value.
|
switch
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def throw(self, *throw_args):
"""Switch to the greenlet with the exception. If there's no greenlet, store the exception."""
greenlet = self.greenlet
if greenlet is None:
self._exception = throw_args
else:
assert getcurrent() is self.hub, "Can only use Waiter.switch method from the Hub greenlet"
throw = greenlet.throw
try:
throw(*throw_args)
except:
self.hub.handle_error(throw, *sys.exc_info())
|
Switch to the greenlet with the exception. If there's no greenlet, store the exception.
|
throw
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def get(self):
"""If a value/an exception is stored, return/raise it. Otherwise until switch() or throw() is called."""
if self._exception is not _NONE:
if self._exception is None:
return self.value
else:
getcurrent().throw(*self._exception)
else:
if self.greenlet is not None:
raise ConcurrentObjectUseError('This Waiter is already used by %r' % (self.greenlet, ))
self.greenlet = getcurrent()
try:
return self.hub.switch()
finally:
self.greenlet = None
|
If a value/an exception is stored, return/raise it. Otherwise until switch() or throw() is called.
|
get
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def iwait(objects, timeout=None, count=None):
"""
Iteratively yield *objects* as they are ready, until all (or *count*) are ready
or *timeout* expired.
:param objects: A sequence (supporting :func:`len`) containing objects
implementing the wait protocol (rawlink() and unlink()).
:keyword int count: If not `None`, then a number specifying the maximum number
of objects to wait for. If ``None`` (the default), all objects
are waited for.
:keyword float timeout: 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.
.. seealso:: :func:`wait`
.. versionchanged:: 1.1a1
Add the *count* parameter.
.. versionchanged:: 1.1a2
No longer raise :exc:`LoopExit` if our caller switches greenlets
in between items yielded by this function.
"""
# QQQ would be nice to support iterable here that can be generated slowly (why?)
if objects is None:
yield get_hub().join(timeout=timeout)
return
count = len(objects) if count is None else min(count, len(objects))
waiter = _MultipleWaiter()
switch = waiter.switch
if timeout is not None:
timer = get_hub().loop.timer(timeout, priority=-1)
timer.start(switch, _NONE)
try:
for obj in objects:
obj.rawlink(switch)
for _ in xrange(count):
item = waiter.get()
waiter.clear()
if item is _NONE:
return
yield item
finally:
if timeout is not None:
timer.stop()
for obj in objects:
unlink = getattr(obj, 'unlink', None)
if unlink:
try:
unlink(switch)
except:
traceback.print_exc()
|
Iteratively yield *objects* as they are ready, until all (or *count*) are ready
or *timeout* expired.
:param objects: A sequence (supporting :func:`len`) containing objects
implementing the wait protocol (rawlink() and unlink()).
:keyword int count: If not `None`, then a number specifying the maximum number
of objects to wait for. If ``None`` (the default), all objects
are waited for.
:keyword float timeout: 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.
.. seealso:: :func:`wait`
.. versionchanged:: 1.1a1
Add the *count* parameter.
.. versionchanged:: 1.1a2
No longer raise :exc:`LoopExit` if our caller switches greenlets
in between items yielded by this function.
|
iwait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def 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):
- :class:`gevent.Greenlet` instance
- :class:`gevent.event.Event` instance
- :class:`gevent.lock.Semaphore` instance
- :class:`gevent.subprocess.Popen` instance
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.
.. seealso:: :func:`iwait`
"""
if objects is None:
return get_hub().join(timeout=timeout)
return list(iwait(objects, timeout, count))
|
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):
- :class:`gevent.Greenlet` instance
- :class:`gevent.event.Event` instance
- :class:`gevent.lock.Semaphore` instance
- :class:`gevent.subprocess.Popen` instance
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.
.. seealso:: :func:`iwait`
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/hub.py
|
MIT
|
def create_dict(self):
"""Create a new dict for the current thread, and return it."""
localdict = {}
key = self.key
thread = getcurrent()
idt = id(thread)
# If we are working with a gevent.greenlet.Greenlet, we can
# pro-actively clear out with a link. Use rawlink to avoid
# spawning any more greenlets
try:
rawlink = thread.rawlink
except AttributeError:
# Otherwise we need to do it with weak refs
def local_deleted(_, key=key):
# When the localimpl is deleted, remove the thread attribute.
thread = wrthread()
if thread is not None:
del thread.__dict__[key]
def thread_deleted(_, idt=idt):
# When the thread is deleted, remove the local dict.
# Note that this is suboptimal if the thread object gets
# caught in a reference loop. We would like to be called
# as soon as the OS-level thread ends instead.
_local = wrlocal()
if _local is not None:
_local.dicts.pop(idt, None)
wrlocal = ref(self, local_deleted)
wrthread = ref(thread, thread_deleted)
thread.__dict__[key] = wrlocal
else:
wrdicts = ref(self.dicts)
def clear(_):
dicts = wrdicts()
if dicts:
dicts.pop(idt, None)
rawlink(clear)
wrthread = None
self.dicts[idt] = wrthread, localdict
return localdict
|
Create a new dict for the current thread, and return it.
|
create_dict
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/local.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/local.py
|
MIT
|
def get_original(mod_name, item_name):
"""Retrieve the original object from a module.
If the object has not been patched, then that object will still be retrieved.
:param item_name: A string or sequence of strings naming the attribute(s) on the module
``mod_name`` to return.
:return: The original value if a string was given for ``item_name`` or a sequence
of original values if a sequence was passed.
"""
if isinstance(item_name, string_types):
return _get_original(mod_name, [item_name])[0]
else:
return _get_original(mod_name, item_name)
|
Retrieve the original object from a module.
If the object has not been patched, then that object will still be retrieved.
:param item_name: A string or sequence of strings naming the attribute(s) on the module
``mod_name`` to return.
:return: The original value if a string was given for ``item_name`` or a sequence
of original values if a sequence was passed.
|
get_original
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/monkey.py
|
MIT
|
def patch_sys(stdin=True, stdout=True, stderr=True):
"""Patch sys.std[in,out,err] to use a cooperative IO via a threadpool.
This is relatively dangerous and can have unintended consequences such as hanging
the process or `misinterpreting control keys`_ when ``input`` and ``raw_input``
are used.
This method does nothing on Python 3. The Python 3 interpreter wants to flush
the TextIOWrapper objects that make up stderr/stdout at shutdown time, but
using a threadpool at that time leads to a hang.
.. _`misinterpreting control keys`: https://github.com/gevent/gevent/issues/274
"""
# test__issue6.py demonstrates the hang if these lines are removed;
# strangely enough that test passes even without monkey-patching sys
if PY3:
return
if stdin:
_patch_sys_std('stdin')
if stdout:
_patch_sys_std('stdout')
if stderr:
_patch_sys_std('stderr')
|
Patch sys.std[in,out,err] to use a cooperative IO via a threadpool.
This is relatively dangerous and can have unintended consequences such as hanging
the process or `misinterpreting control keys`_ when ``input`` and ``raw_input``
are used.
This method does nothing on Python 3. The Python 3 interpreter wants to flush
the TextIOWrapper objects that make up stderr/stdout at shutdown time, but
using a threadpool at that time leads to a hang.
.. _`misinterpreting control keys`: https://github.com/gevent/gevent/issues/274
|
patch_sys
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/monkey.py
|
MIT
|
def patch_time():
"""Replace :func:`time.sleep` with :func:`gevent.sleep`."""
from gevent.hub import sleep
import time
patch_item(time, 'sleep', sleep)
|
Replace :func:`time.sleep` with :func:`gevent.sleep`.
|
patch_time
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/monkey.py
|
MIT
|
def patch_thread(threading=True, _threading_local=True, Event=False, logging=True,
existing_locks=True,
_warnings=None):
"""
Replace the standard :mod:`thread` module to make it greenlet-based.
- If *threading* is true (the default), also patch ``threading``.
- If *_threading_local* is true (the default), also patch ``_threading_local.local``.
- If *logging* is True (the default), also patch locks taken if the logging module has
been configured.
- If *existing_locks* is True (the default), and the process is still single threaded,
make sure than any :class:`threading.RLock` (and, under Python 3, :class:`importlib._bootstrap._ModuleLock`)
instances that are currently locked can be properly unlocked.
.. caution::
Monkey-patching :mod:`thread` and using
:class:`multiprocessing.Queue` or
:class:`concurrent.futures.ProcessPoolExecutor` (which uses a
``Queue``) will hang the process.
.. versionchanged:: 1.1b1
Add *logging* and *existing_locks* params.
"""
# Description of the hang:
# There is an incompatibility with patching 'thread' and the 'multiprocessing' module:
# The problem is that multiprocessing.queues.Queue uses a half-duplex multiprocessing.Pipe,
# which is implemented with os.pipe() and _multiprocessing.Connection. os.pipe isn't patched
# by gevent, as it returns just a fileno. _multiprocessing.Connection is an internal implementation
# class implemented in C, which exposes a 'poll(timeout)' method; under the covers, this issues a
# (blocking) select() call: hence the need for a real thread. Except for that method, we could
# almost replace Connection with gevent.fileobject.SocketAdapter, plus a trivial
# patch to os.pipe (below). Sigh, so close. (With a little work, we could replicate that method)
# import os
# import fcntl
# os_pipe = os.pipe
# def _pipe():
# r, w = os_pipe()
# fcntl.fcntl(r, fcntl.F_SETFL, os.O_NONBLOCK)
# fcntl.fcntl(w, fcntl.F_SETFL, os.O_NONBLOCK)
# return r, w
# os.pipe = _pipe
# The 'threading' module copies some attributes from the
# thread module the first time it is imported. If we patch 'thread'
# before that happens, then we store the wrong values in 'saved',
# So if we're going to patch threading, we either need to import it
# before we patch thread, or manually clean up the attributes that
# are in trouble. The latter is tricky because of the different names
# on different versions.
if threading:
__import__('threading')
patch_module('thread')
if threading:
threading = patch_module('threading')
if Event:
from gevent.event import Event
patch_item(threading, 'Event', Event)
if existing_locks:
_patch_existing_locks(threading)
if logging and 'logging' in sys.modules:
logging = __import__('logging')
patch_item(logging, '_lock', threading.RLock())
for wr in logging._handlerList:
# In py26, these are actual handlers, not weakrefs
handler = wr() if callable(wr) else wr
if handler is None:
continue
if not hasattr(handler, 'lock'):
raise TypeError("Unknown/unsupported handler %r" % handler)
handler.lock = threading.RLock()
if _threading_local:
_threading_local = __import__('_threading_local')
from gevent.local import local
patch_item(_threading_local, 'local', local)
if sys.version_info[:2] >= (3, 4):
# Issue 18808 changes the nature of Thread.join() to use
# locks. This means that a greenlet spawned in the main thread
# (which is already running) cannot wait for the main thread---it
# hangs forever. We patch around this if possible. See also
# gevent.threading.
threading = __import__('threading')
greenlet = __import__('greenlet')
if threading.current_thread() == threading.main_thread():
main_thread = threading.main_thread()
_greenlet = main_thread._greenlet = greenlet.getcurrent()
from gevent.hub import sleep
def join(timeout=None):
if threading.current_thread() is main_thread:
raise RuntimeError("Cannot join current thread")
if _greenlet.dead or not main_thread.is_alive():
return
elif timeout:
raise ValueError("Cannot use a timeout to join the main thread")
# XXX: Make that work
else:
while main_thread.is_alive():
sleep(0.01)
main_thread.join = join
# Patch up the ident of the main thread to match. This
# matters if threading was imported before monkey-patching
# thread
oldid = main_thread.ident
main_thread._ident = threading.get_ident()
if oldid in threading._active:
threading._active[main_thread.ident] = threading._active[oldid]
if oldid != main_thread.ident:
del threading._active[oldid]
else:
_queue_warning("Monkey-patching not on the main thread; "
"threading.main_thread().join() will hang from a greenlet",
_warnings)
|
Replace the standard :mod:`thread` module to make it greenlet-based.
- If *threading* is true (the default), also patch ``threading``.
- If *_threading_local* is true (the default), also patch ``_threading_local.local``.
- If *logging* is True (the default), also patch locks taken if the logging module has
been configured.
- If *existing_locks* is True (the default), and the process is still single threaded,
make sure than any :class:`threading.RLock` (and, under Python 3, :class:`importlib._bootstrap._ModuleLock`)
instances that are currently locked can be properly unlocked.
.. caution::
Monkey-patching :mod:`thread` and using
:class:`multiprocessing.Queue` or
:class:`concurrent.futures.ProcessPoolExecutor` (which uses a
``Queue``) will hang the process.
.. versionchanged:: 1.1b1
Add *logging* and *existing_locks* params.
|
patch_thread
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/monkey.py
|
MIT
|
def patch_socket(dns=True, aggressive=True):
"""Replace the standard socket object with gevent's cooperative sockets.
If ``dns`` is true, also patch dns functions in :mod:`socket`.
"""
from gevent import socket
# Note: although it seems like it's not strictly necessary to monkey patch 'create_connection',
# it's better to do it. If 'create_connection' was not monkey patched, but the rest of socket module
# was, create_connection would still use "green" getaddrinfo and "green" socket.
# However, because gevent.socket.socket.connect is a Python function, the exception raised by it causes
# _socket object to be referenced by the frame, thus causing the next invocation of bind(source_address) to fail.
if dns:
items = socket.__implements__
else:
items = set(socket.__implements__) - set(socket.__dns__)
patch_module('socket', items=items)
if aggressive:
if 'ssl' not in socket.__implements__:
remove_item(socket, 'ssl')
|
Replace the standard socket object with gevent's cooperative sockets.
If ``dns`` is true, also patch dns functions in :mod:`socket`.
|
patch_socket
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/monkey.py
|
MIT
|
def patch_select(aggressive=True):
"""
Replace :func:`select.select` with :func:`gevent.select.select`
and :func:`select.poll` with :class:`gevent.select.poll` (where available).
If ``aggressive`` is true (the default), also remove other
blocking functions from :mod:`select` and (on Python 3.4 and
above) :mod:`selectors`:
- :func:`select.epoll`
- :func:`select.kqueue`
- :func:`select.kevent`
- :func:`select.devpoll` (Python 3.5+)
- :class:`selectors.EpollSelector`
- :class:`selectors.KqueueSelector`
- :class:`selectors.DevpollSelector` (Python 3.5+)
"""
patch_module('select')
if aggressive:
select = __import__('select')
# since these are blocking we're removing them here. This makes some other
# modules (e.g. asyncore) non-blocking, as they use select that we provide
# when none of these are available.
remove_item(select, 'epoll')
remove_item(select, 'kqueue')
remove_item(select, 'kevent')
remove_item(select, 'devpoll')
if sys.version_info[:2] >= (3, 4):
# Python 3 wants to use `select.select` as a member function,
# leading to this error in selectors.py (because gevent.select.select is
# not a builtin and doesn't get the magic auto-static that they do)
# r, w, _ = self._select(self._readers, self._writers, [], timeout)
# TypeError: select() takes from 3 to 4 positional arguments but 5 were given
# Note that this obviously only happens if selectors was imported after we had patched
# select; but there is a code path that leads to it being imported first (but now we've
# patched select---so we can't compare them identically)
select = __import__('select') # Should be gevent-patched now
orig_select_select = get_original('select', 'select')
assert select.select is not orig_select_select
selectors = __import__('selectors')
if selectors.SelectSelector._select in (select.select, orig_select_select):
def _select(self, *args, **kwargs): # pylint:disable=unused-argument
return select.select(*args, **kwargs)
selectors.SelectSelector._select = _select
_select._gevent_monkey = True
if aggressive:
# If `selectors` had already been imported before we removed
# select.epoll|kqueue|devpoll, these may have been defined in terms
# of those functions. They'll fail at runtime.
remove_item(selectors, 'EpollSelector')
remove_item(selectors, 'KqueueSelector')
remove_item(selectors, 'DevpollSelector')
selectors.DefaultSelector = selectors.SelectSelector
|
Replace :func:`select.select` with :func:`gevent.select.select`
and :func:`select.poll` with :class:`gevent.select.poll` (where available).
If ``aggressive`` is true (the default), also remove other
blocking functions from :mod:`select` and (on Python 3.4 and
above) :mod:`selectors`:
- :func:`select.epoll`
- :func:`select.kqueue`
- :func:`select.kevent`
- :func:`select.devpoll` (Python 3.5+)
- :class:`selectors.EpollSelector`
- :class:`selectors.KqueueSelector`
- :class:`selectors.DevpollSelector` (Python 3.5+)
|
patch_select
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/monkey.py
|
MIT
|
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True, httplib=False,
subprocess=True, sys=False, aggressive=True, Event=False,
builtins=True, signal=True):
"""
Do all of the default monkey patching (calls every other applicable
function in this module).
.. versionchanged:: 1.1
Issue a :mod:`warning <warnings>` if this function is called multiple times
with different arguments. The second and subsequent calls will only add more
patches, they can never remove existing patches by setting an argument to ``False``.
.. versionchanged:: 1.1
Issue a :mod:`warning <warnings>` if this function is called with ``os=False``
and ``signal=True``. This will cause SIGCHLD handlers to not be called. This may
be an error in the future.
"""
# Check to see if they're changing the patched list
_warnings, first_time = _check_repatching(**locals())
if not _warnings and not first_time:
# Nothing to do, identical args to what we just
# did
return
# order is important
if os:
patch_os()
if time:
patch_time()
if thread:
patch_thread(Event=Event)
# sys must be patched after thread. in other cases threading._shutdown will be
# initiated to _MainThread with real thread ident
if sys:
patch_sys()
if socket:
patch_socket(dns=dns, aggressive=aggressive)
if select:
patch_select(aggressive=aggressive)
if ssl:
patch_ssl()
if httplib:
raise ValueError('gevent.httplib is no longer provided, httplib must be False')
if subprocess:
patch_subprocess()
if builtins:
patch_builtins()
if signal:
if not os:
_queue_warning('Patching signal but not os will result in SIGCHLD handlers'
' installed after this not being called and os.waitpid may not'
' function correctly if gevent.subprocess is used. This may raise an'
' error in the future.',
_warnings)
patch_signal()
_process_warnings(_warnings)
|
Do all of the default monkey patching (calls every other applicable
function in this module).
.. versionchanged:: 1.1
Issue a :mod:`warning <warnings>` if this function is called multiple times
with different arguments. The second and subsequent calls will only add more
patches, they can never remove existing patches by setting an argument to ``False``.
.. versionchanged:: 1.1
Issue a :mod:`warning <warnings>` if this function is called with ``os=False``
and ``signal=True``. This will cause SIGCHLD handlers to not be called. This may
be an error in the future.
|
patch_all
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/monkey.py
|
MIT
|
def make_nonblocking(fd):
"""Put the file descriptor *fd* into non-blocking mode if possible.
:return: A boolean value that evaluates to True if successful."""
flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
if not bool(flags & os.O_NONBLOCK):
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
return True
|
Put the file descriptor *fd* into non-blocking mode if possible.
:return: A boolean value that evaluates to True if successful.
|
make_nonblocking
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def nb_read(fd, n):
"""Read up to `n` bytes from file descriptor `fd`. Return a string
containing the bytes read. If end-of-file is reached, an empty string
is returned.
The descriptor must be in non-blocking mode.
"""
hub, event = None, None
while True:
try:
return _read(fd, n)
except OSError as e:
if e.errno not in ignored_errors:
raise
if not PY3:
sys.exc_clear()
if hub is None:
hub = get_hub()
event = hub.loop.io(fd, 1)
hub.wait(event)
|
Read up to `n` bytes from file descriptor `fd`. Return a string
containing the bytes read. If end-of-file is reached, an empty string
is returned.
The descriptor must be in non-blocking mode.
|
nb_read
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def nb_write(fd, buf):
"""Write bytes from buffer `buf` to file descriptor `fd`. Return the
number of bytes written.
The file descriptor must be in non-blocking mode.
"""
hub, event = None, None
while True:
try:
return _write(fd, buf)
except OSError as e:
if e.errno not in ignored_errors:
raise
if not PY3:
sys.exc_clear()
if hub is None:
hub = get_hub()
event = hub.loop.io(fd, 2)
hub.wait(event)
|
Write bytes from buffer `buf` to file descriptor `fd`. Return the
number of bytes written.
The file descriptor must be in non-blocking mode.
|
nb_write
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def fork_gevent():
"""
Forks the process using :func:`os.fork` and prepares the
child process to continue using gevent before returning.
.. note::
The PID returned by this function may not be waitable with
either the original :func:`os.waitpid` or this module's
:func:`waitpid` and it may not generate SIGCHLD signals if
libev child watchers are or ever have been in use. For
example, the :mod:`gevent.subprocess` module uses libev
child watchers (which parts of gevent use libev child
watchers is subject to change at any time). Most
applications should use :func:`fork_and_watch`, which is
monkey-patched as the default replacement for
:func:`os.fork` and implements the ``fork`` function of
this module by default, unless the environment variable
``GEVENT_NOWAITPID`` is defined before this module is
imported.
.. versionadded:: 1.1b2
"""
result = _raw_fork()
if not result:
reinit()
return result
|
Forks the process using :func:`os.fork` and prepares the
child process to continue using gevent before returning.
.. note::
The PID returned by this function may not be waitable with
either the original :func:`os.waitpid` or this module's
:func:`waitpid` and it may not generate SIGCHLD signals if
libev child watchers are or ever have been in use. For
example, the :mod:`gevent.subprocess` module uses libev
child watchers (which parts of gevent use libev child
watchers is subject to change at any time). Most
applications should use :func:`fork_and_watch`, which is
monkey-patched as the default replacement for
:func:`os.fork` and implements the ``fork`` function of
this module by default, unless the environment variable
``GEVENT_NOWAITPID`` is defined before this module is
imported.
.. versionadded:: 1.1b2
|
fork_gevent
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def waitpid(pid, options):
"""
Wait for a child process to finish.
If the child process was spawned using :func:`fork_and_watch`, then this
function behaves cooperatively. If not, it *may* have race conditions; see
:func:`fork_gevent` for more information.
The arguments are as for the underlying :func:`os.waitpid`. Some combinations
of *options* may not be supported (as of 1.1 that includes WUNTRACED).
Availability: POSIX.
.. versionadded:: 1.1b1
"""
# XXX Does not handle tracing children
if pid <= 0:
# magic functions for multiple children.
if pid == -1:
# Any child. If we have one that we're watching and that finished,
# we need to use that one. Otherwise, let the OS take care of it.
for k, v in _watched_children.items():
if isinstance(v, tuple):
pid = k
break
if pid <= 0:
# If we didn't find anything, go to the OS. Otherwise,
# handle waiting
return _waitpid(pid, options)
if pid in _watched_children:
# yes, we're watching it
if options & _WNOHANG or isinstance(_watched_children[pid], tuple):
# We're either asked not to block, or it already finished, in which
# case blocking doesn't matter
result = _watched_children[pid]
if isinstance(result, tuple):
# it finished. libev child watchers
# are one-shot
del _watched_children[pid]
return result[:2]
# it's not finished
return (0, 0)
else:
# we should block. Let the underlying OS call block; it should
# eventually die with OSError, depending on signal delivery
try:
return _waitpid(pid, options)
except OSError:
if pid in _watched_children and isinstance(_watched_children, tuple):
result = _watched_children[pid]
del _watched_children[pid]
return result[:2]
raise
# we're not watching it
return _waitpid(pid, options)
|
Wait for a child process to finish.
If the child process was spawned using :func:`fork_and_watch`, then this
function behaves cooperatively. If not, it *may* have race conditions; see
:func:`fork_gevent` for more information.
The arguments are as for the underlying :func:`os.waitpid`. Some combinations
of *options* may not be supported (as of 1.1 that includes WUNTRACED).
Availability: POSIX.
.. versionadded:: 1.1b1
|
waitpid
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def fork_and_watch(callback=None, loop=None, ref=False, fork=fork_gevent):
"""
Fork a child process and start a child watcher for it in the parent process.
This call cooperates with :func:`waitpid` to enable cooperatively waiting
for children to finish. When monkey-patching, these functions are patched in as
:func:`os.fork` and :func:`os.waitpid`, respectively.
In the child process, this function calls :func:`gevent.hub.reinit` before returning.
Availability: POSIX.
:keyword callback: If given, a callable that will be called with the child watcher
when the child finishes.
:keyword loop: The loop to start the watcher in. Defaults to the
loop of the current hub.
:keyword fork: The fork function. Defaults to :func:`the one defined in this
module <gevent.os.fork_gevent>` (which automatically calls :func:`gevent.hub.reinit`).
Pass the builtin :func:`os.fork` function if you do not need to
initialize gevent in the child process.
.. versionadded:: 1.1b1
.. seealso::
:func:`gevent.monkey.get_original` To access the builtin :func:`os.fork`.
"""
pid = fork()
if pid:
# parent
loop = loop or get_hub().loop
watcher = loop.child(pid, ref=ref)
_watched_children[pid] = watcher
watcher.start(_on_child, watcher, callback)
return pid
|
Fork a child process and start a child watcher for it in the parent process.
This call cooperates with :func:`waitpid` to enable cooperatively waiting
for children to finish. When monkey-patching, these functions are patched in as
:func:`os.fork` and :func:`os.waitpid`, respectively.
In the child process, this function calls :func:`gevent.hub.reinit` before returning.
Availability: POSIX.
:keyword callback: If given, a callable that will be called with the child watcher
when the child finishes.
:keyword loop: The loop to start the watcher in. Defaults to the
loop of the current hub.
:keyword fork: The fork function. Defaults to :func:`the one defined in this
module <gevent.os.fork_gevent>` (which automatically calls :func:`gevent.hub.reinit`).
Pass the builtin :func:`os.fork` function if you do not need to
initialize gevent in the child process.
.. versionadded:: 1.1b1
.. seealso::
:func:`gevent.monkey.get_original` To access the builtin :func:`os.fork`.
|
fork_and_watch
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def forkpty_and_watch(callback=None, loop=None, ref=False, forkpty=forkpty_gevent):
"""
Like :func:`fork_and_watch`, except using :func:`forkpty_gevent`.
Availability: Some Unix systems.
.. versionadded:: 1.1b5
"""
result = []
def _fork():
pid_and_fd = forkpty()
result.append(pid_and_fd)
return pid_and_fd[0]
fork_and_watch(callback, loop, ref, _fork)
return result[0]
|
Like :func:`fork_and_watch`, except using :func:`forkpty_gevent`.
Availability: Some Unix systems.
.. versionadded:: 1.1b5
|
forkpty_and_watch
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def fork(*args, **kwargs):
"""
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 :func:`fork_and_watch`
when the environment variable ``GEVENT_NOWAITPID`` is *not* defined.
This is the default and should be used by most applications.
.. versionchanged:: 1.1b2
"""
# take any args to match fork_and_watch
return fork_and_watch(*args, **kwargs)
|
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 :func:`fork_and_watch`
when the environment variable ``GEVENT_NOWAITPID`` is *not* defined.
This is the default and should be used by most applications.
.. versionchanged:: 1.1b2
|
fork
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def forkpty(*args, **kwargs):
"""
Like :func:`fork`, but using :func:`forkpty_gevent`.
This implementation of ``forkpty`` is a wrapper for :func:`forkpty_and_watch`
when the environment variable ``GEVENT_NOWAITPID`` is *not* defined.
This is the default and should be used by most applications.
.. versionadded:: 1.1b5
"""
# take any args to match fork_and_watch
return forkpty_and_watch(*args, **kwargs)
|
Like :func:`fork`, but using :func:`forkpty_gevent`.
This implementation of ``forkpty`` is a wrapper for :func:`forkpty_and_watch`
when the environment variable ``GEVENT_NOWAITPID`` is *not* defined.
This is the default and should be used by most applications.
.. versionadded:: 1.1b5
|
forkpty
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/os.py
|
MIT
|
def __init__(self, func, iterable, spawn=None, maxsize=None, _zipped=False):
"""
An iterator that.
:keyword int maxsize: If given and not-None, specifies the maximum number of
finished results that will be allowed to accumulated awaiting the reader;
more than that number of results will cause map function greenlets to begin
to block. This is most useful is there is a great disparity in the speed of
the mapping code and the consumer and the results consume a great deal of resources.
Using a bound is more computationally expensive than not using a bound.
.. versionchanged:: 1.1b3
Added the *maxsize* parameter.
"""
from gevent.queue import Queue
Greenlet.__init__(self)
if spawn is not None:
self.spawn = spawn
if _zipped:
self._zipped = _zipped
self.func = func
self.iterable = iterable
self.queue = Queue()
if maxsize:
# Bounding the queue is not enough if we want to keep from
# accumulating objects; the result value will be around as
# the greenlet's result, blocked on self.queue.put(), and
# we'll go on to spawn another greenlet, which in turn can
# create the result. So we need a semaphore to prevent a
# greenlet from exiting while the queue is full so that we
# don't spawn the next greenlet (assuming that self.spawn
# is of course bounded). (Alternatively we could have the
# greenlet itself do the insert into the pool, but that
# takes some rework).
#
# Given the use of a semaphore at this level, sizing the queue becomes
# redundant, and that lets us avoid having to use self.link() instead
# of self.rawlink() to avoid having blocking methods called in the
# hub greenlet.
self._result_semaphore = Semaphore(maxsize)
else:
self._result_semaphore = DummySemaphore()
self.count = 0
self.finished = False
# If the queue size is unbounded, then we want to call all
# the links (_on_finish and _on_result) directly in the hub greenlet
# for efficiency. However, if the queue is bounded, we can't do that if
# the queue might block (because if there's no waiter the hub can switch to,
# the queue simply raises Full). Therefore, in that case, we use
# the safer, somewhat-slower (because it spawns a greenlet) link() methods.
# This means that _on_finish and _on_result can be called and interleaved in any order
# if the call to self.queue.put() blocks..
# Note that right now we're not bounding the queue, instead using a semaphore.
self.rawlink(self._on_finish)
|
An iterator that.
:keyword int maxsize: If given and not-None, specifies the maximum number of
finished results that will be allowed to accumulated awaiting the reader;
more than that number of results will cause map function greenlets to begin
to block. This is most useful is there is a great disparity in the speed of
the mapping code and the consumer and the results consume a great deal of resources.
Using a bound is more computationally expensive than not using a bound.
.. versionchanged:: 1.1b3
Added the *maxsize* parameter.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def apply_cb(self, func, args=None, kwds=None, callback=None):
"""
:meth:`apply` the given *func*, and, if a *callback* is given, run it with the
results of *func* (unless an exception was raised.)
The *callback* may be called synchronously or asynchronously. If called
asynchronously, it will not be tracked by this group. (:class:`Group` and :class:`Pool`
call it asynchronously in a new greenlet; :class:`~gevent.threadpool.ThreadPool` calls
it synchronously in the current greenlet.)
"""
result = self.apply(func, args, kwds)
if callback is not None:
self._apply_async_cb_spawn(callback, result)
return result
|
:meth:`apply` the given *func*, and, if a *callback* is given, run it with the
results of *func* (unless an exception was raised.)
The *callback* may be called synchronously or asynchronously. If called
asynchronously, it will not be tracked by this group. (:class:`Group` and :class:`Pool`
call it asynchronously in a new greenlet; :class:`~gevent.threadpool.ThreadPool` calls
it synchronously in the current greenlet.)
|
apply_cb
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def apply_async(self, func, args=None, kwds=None, callback=None):
"""
A variant of the apply() method which returns a Greenlet object.
If *callback* is specified, then it should be a callable which
accepts a single argument. When the result becomes ready
callback is applied to it (unless the call failed).
"""
if args is None:
args = ()
if kwds is None:
kwds = {}
if self._apply_async_use_greenlet():
# cannot call spawn() directly because it will block
return Greenlet.spawn(self.apply_cb, func, args, kwds, callback)
greenlet = self.spawn(func, *args, **kwds)
if callback is not None:
greenlet.link(pass_value(callback))
return greenlet
|
A variant of the apply() method which returns a Greenlet object.
If *callback* is specified, then it should be a callable which
accepts a single argument. When the result becomes ready
callback is applied to it (unless the call failed).
|
apply_async
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def apply(self, func, args=None, kwds=None):
"""
Rough quivalent 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.
Any exception ``func`` raises will be propagated to the caller of ``apply`` (that is,
this method will raise the exception that ``func`` raised).
"""
if args is None:
args = ()
if kwds is None:
kwds = {}
if self._apply_immediately():
return func(*args, **kwds)
else:
return self.spawn(func, *args, **kwds).get()
|
Rough quivalent 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.
Any exception ``func`` raises will be propagated to the caller of ``apply`` (that is,
this method will raise the exception that ``func`` raised).
|
apply
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def add(self, greenlet):
"""
Begin tracking the greenlet.
If this group is :meth:`full`, then this method may block
until it is possible to track the greenlet.
"""
try:
rawlink = greenlet.rawlink
except AttributeError:
pass # non-Greenlet greenlet, like MAIN
else:
rawlink(self._discard)
self.greenlets.add(greenlet)
self._empty_event.clear()
|
Begin tracking the greenlet.
If this group is :meth:`full`, then this method may block
until it is possible to track the greenlet.
|
add
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def spawn(self, *args, **kwargs):
"""
Begin a new greenlet with the given arguments (which are passed
to the greenlet constructor) and add it to the collection of greenlets
this group is monitoring.
:return: The newly started greenlet.
"""
greenlet = self.greenlet_class(*args, **kwargs)
self.start(greenlet)
return greenlet
|
Begin a new greenlet with the given arguments (which are passed
to the greenlet constructor) and add it to the collection of greenlets
this group is monitoring.
:return: The newly started greenlet.
|
spawn
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def join(self, timeout=None, raise_error=False):
"""
Wait for this group to become empty *at least once*.
If there are no greenlets in the group, returns immediately.
.. note:: By the time the waiting code (the caller of this
method) regains control, a greenlet may have been added to
this group, and so this object may no longer be empty. (That
is, ``group.join(); assert len(group) == 0`` is not
guaranteed to hold.) This method only guarantees that the group
reached a ``len`` of 0 at some point.
:keyword bool raise_error: If True (*not* the default), if any
greenlet that finished while the join was in progress raised
an exception, that exception will be raised to the caller of
this method. If multiple greenlets raised exceptions, which
one gets re-raised is not determined. Only greenlets currently
in the group when this method is called are guaranteed to
be checked for exceptions.
"""
if raise_error:
greenlets = self.greenlets.copy()
self._empty_event.wait(timeout=timeout)
for greenlet in greenlets:
if greenlet.exception is not None:
if hasattr(greenlet, '_raise_exception'):
greenlet._raise_exception()
raise greenlet.exception
else:
self._empty_event.wait(timeout=timeout)
|
Wait for this group to become empty *at least once*.
If there are no greenlets in the group, returns immediately.
.. note:: By the time the waiting code (the caller of this
method) regains control, a greenlet may have been added to
this group, and so this object may no longer be empty. (That
is, ``group.join(); assert len(group) == 0`` is not
guaranteed to hold.) This method only guarantees that the group
reached a ``len`` of 0 at some point.
:keyword bool raise_error: If True (*not* the default), if any
greenlet that finished while the join was in progress raised
an exception, that exception will be raised to the caller of
this method. If multiple greenlets raised exceptions, which
one gets re-raised is not determined. Only greenlets currently
in the group when this method is called are guaranteed to
be checked for exceptions.
|
join
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def kill(self, exception=GreenletExit, block=True, timeout=None):
"""
Kill all greenlets being tracked by this group.
"""
timer = Timeout._start_new_or_dummy(timeout)
try:
try:
while self.greenlets:
for greenlet in list(self.greenlets):
if greenlet not in self.dying:
try:
kill = greenlet.kill
except AttributeError:
_kill(greenlet, exception)
else:
kill(exception, block=False)
self.dying.add(greenlet)
if not block:
break
joinall(self.greenlets)
except Timeout as ex:
if ex is not timer:
raise
finally:
timer.cancel()
|
Kill all greenlets being tracked by this group.
|
kill
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def killone(self, greenlet, exception=GreenletExit, block=True, timeout=None):
"""
If the given *greenlet* is running and being tracked by this group,
kill it.
"""
if greenlet not in self.dying and greenlet in self.greenlets:
greenlet.kill(exception, block=False)
self.dying.add(greenlet)
if block:
greenlet.join(timeout)
|
If the given *greenlet* is running and being tracked by this group,
kill it.
|
killone
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def free_count(self):
"""
Return a number indicating *approximately* how many more members
can be added to this pool.
"""
if self.size is None:
return 1
return max(0, self.size - len(self))
|
Return a number indicating *approximately* how many more members
can be added to this pool.
|
free_count
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def add(self, greenlet):
"""
Begin tracking the given greenlet, blocking until space is available.
.. seealso:: :meth:`Group.add`
"""
self._semaphore.acquire()
try:
Group.add(self, greenlet)
except:
self._semaphore.release()
raise
|
Begin tracking the given greenlet, blocking until space is available.
.. seealso:: :meth:`Group.add`
|
add
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pool.py
|
MIT
|
def handle(self):
"""
The main request handling method, called by the server.
This method runs a request handling loop, calling
:meth:`handle_one_request` until all requests on the
connection have been handled (that is, it implements
keep-alive).
"""
try:
while self.socket is not None:
self.time_start = time.time()
self.time_finish = 0
result = self.handle_one_request()
if result is None:
break
if result is True:
continue
self.status, response_body = result
self.socket.sendall(response_body)
if self.time_finish == 0:
self.time_finish = time.time()
self.log_request()
break
finally:
if self.socket is not None:
_sock = getattr(self.socket, '_sock', None) # Python 3
try:
# read out request data to prevent error: [Errno 104] Connection reset by peer
if _sock:
try:
# socket.recv would hang
_sock.recv(16384)
finally:
_sock.close()
self.socket.close()
except socket.error:
pass
self.__dict__.pop('socket', None)
self.__dict__.pop('rfile', None)
|
The main request handling method, called by the server.
This method runs a request handling loop, calling
:meth:`handle_one_request` until all requests on the
connection have been handled (that is, it implements
keep-alive).
|
handle
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pywsgi.py
|
MIT
|
def read_request(self, raw_requestline):
"""
Parse the incoming request.
Parses various headers into ``self.headers`` using
:attr:`MessageClass`. Other attributes that are set upon a successful
return of this method include ``self.content_length`` and ``self.close_connection``.
:param str raw_requestline: A native :class:`str` representing
the request line. A processed version of this will be stored
into ``self.requestline``.
:raises ValueError: If the request is invalid. This error will
not be logged as a traceback (because it's a client issue, not a server problem).
:return: A boolean value indicating whether the request was successfully parsed.
This method should either return a true value or have raised a ValueError
with details about the parsing error.
.. versionchanged:: 1.1b6
Raise the previously documented :exc:`ValueError` in more cases instead of returning a
false value; this allows subclasses more opportunity to customize behaviour.
"""
self.requestline = raw_requestline.rstrip()
words = self.requestline.split()
if len(words) == 3:
self.command, self.path, self.request_version = words
if not self._check_http_version():
raise _InvalidClientRequest('Invalid http version: %r', raw_requestline)
elif len(words) == 2:
self.command, self.path = words
if self.command != "GET":
raise _InvalidClientRequest('Expected GET method: %r', raw_requestline)
self.request_version = "HTTP/0.9"
# QQQ I'm pretty sure we can drop support for HTTP/0.9
else:
raise _InvalidClientRequest('Invalid HTTP method: %r', raw_requestline)
self.headers = self.MessageClass(self.rfile, 0)
if self.headers.status:
raise _InvalidClientRequest('Invalid headers status: %r', self.headers.status)
if self.headers.get("transfer-encoding", "").lower() == "chunked":
try:
del self.headers["content-length"]
except KeyError:
pass
content_length = self.headers.get("content-length")
if content_length is not None:
content_length = int(content_length)
if content_length < 0:
raise _InvalidClientRequest('Invalid Content-Length: %r', content_length)
if content_length and self.command in ('HEAD', ):
raise _InvalidClientRequest('Unexpected Content-Length')
self.content_length = content_length
if self.request_version == "HTTP/1.1":
conntype = self.headers.get("Connection", "").lower()
if conntype == "close":
self.close_connection = True
else:
self.close_connection = False
else:
self.close_connection = True
return True
|
Parse the incoming request.
Parses various headers into ``self.headers`` using
:attr:`MessageClass`. Other attributes that are set upon a successful
return of this method include ``self.content_length`` and ``self.close_connection``.
:param str raw_requestline: A native :class:`str` representing
the request line. A processed version of this will be stored
into ``self.requestline``.
:raises ValueError: If the request is invalid. This error will
not be logged as a traceback (because it's a client issue, not a server problem).
:return: A boolean value indicating whether the request was successfully parsed.
This method should either return a true value or have raised a ValueError
with details about the parsing error.
.. versionchanged:: 1.1b6
Raise the previously documented :exc:`ValueError` in more cases instead of returning a
false value; this allows subclasses more opportunity to customize behaviour.
|
read_request
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pywsgi.py
|
MIT
|
def read_requestline(self):
"""
Read and return the HTTP request line.
Under both Python 2 and 3, this should return the native
``str`` type; under Python 3, this probably means the bytes read
from the network need to be decoded (using the ISO-8859-1 charset, aka
latin-1).
"""
line = self.rfile.readline(MAX_REQUEST_LINE)
if PY3:
line = line.decode('latin-1')
return line
|
Read and return the HTTP request line.
Under both Python 2 and 3, this should return the native
``str`` type; under Python 3, this probably means the bytes read
from the network need to be decoded (using the ISO-8859-1 charset, aka
latin-1).
|
read_requestline
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pywsgi.py
|
MIT
|
def start_response(self, status, headers, exc_info=None):
"""
.. versionchanged:: 1.1b5
Pro-actively handle checking the encoding of the status line
and headers during this method. On Python 2, avoid some
extra encodings.
"""
if exc_info:
try:
if self.headers_sent:
# Re-raise original exception if headers sent
reraise(*exc_info)
finally:
# Avoid dangling circular ref
exc_info = None
# Pep 3333, "The start_response callable":
# https://www.python.org/dev/peps/pep-3333/#the-start-response-callable
# "Servers should check for errors in the headers at the time
# start_response is called, so that an error can be raised
# while the application is still running." Here, we check the encoding.
# This aids debugging: headers especially are generated programatically
# and an encoding error in a loop or list comprehension yields an opaque
# UnicodeError without any clue which header was wrong.
# Note that this results in copying the header list at this point, not modifying it,
# although we are allowed to do so if needed. This slightly increases memory usage.
response_headers = []
header = None
value = None
try:
for header, value in headers:
if not isinstance(header, str):
raise UnicodeError("The header must be a native string", header, value)
if not isinstance(value, str):
raise UnicodeError("The value must be a native string", header, value)
# Either we're on Python 2, in which case bytes is correct, or
# we're on Python 3 and the user screwed up (because it should be a native
# string). In either case, make sure that this is latin-1 compatible. Under
# Python 2, bytes.encode() will take a round-trip through the system encoding,
# which may be ascii, which is not really what we want. However, the latin-1 encoding
# can encode everything except control characters and the block from 0x7F to 0x9F, so
# explicitly round-tripping bytes through the encoding is unlikely to be of much
# benefit, so we go for speed (the WSGI spec specifically calls out allowing the range
# from 0x00 to 0xFF, although the HTTP spec forbids the control characters).
# Note: Some Python 2 implementations, like Jython, may allow non-octet (above 255) values
# in their str implementation; this is mentioned in the WSGI spec, but we don't
# run on any platform like that so we can assume that a str value is pure bytes.
response_headers.append((header if not PY3 else header.encode("latin-1"),
value if not PY3 else value.encode("latin-1")))
except UnicodeEncodeError:
# If we get here, we're guaranteed to have a header and value
raise UnicodeError("Non-latin1 header", header, value)
# Same as above
if not isinstance(status, str):
raise UnicodeError("The status string must be a native string")
# don't assign to anything until the validation is complete, including parsing the
# code
code = int(status.split(' ', 1)[0])
self.status = status if not PY3 else status.encode("latin-1")
self._orig_status = status # Preserve the native string for logging
self.response_headers = response_headers
self.code = code
provided_connection = None
self.provided_date = None
self.provided_content_length = None
for header, value in headers:
header = header.lower()
if header == 'connection':
provided_connection = value
elif header == 'date':
self.provided_date = value
elif header == 'content-length':
self.provided_content_length = value
if self.request_version == 'HTTP/1.0' and provided_connection is None:
response_headers.append((b'Connection', b'close'))
self.close_connection = True
elif provided_connection == 'close':
self.close_connection = True
if self.code in (304, 204):
if self.provided_content_length is not None and self.provided_content_length != '0':
msg = 'Invalid Content-Length for %s response: %r (must be absent or zero)' % (self.code, self.provided_content_length)
if PY3:
msg = msg.encode('latin-1')
raise AssertionError(msg)
return self.write
|
.. versionchanged:: 1.1b5
Pro-actively handle checking the encoding of the status line
and headers during this method. On Python 2, avoid some
extra encodings.
|
start_response
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pywsgi.py
|
MIT
|
def get_environ(self):
"""
Construct and return a new WSGI environment dictionary for a specific request.
This should begin with asking the server for the base environment
using :meth:`WSGIServer.get_environ`, and then proceed to add the
request specific values.
By the time this method is invoked the request line and request shall have
been parsed and ``self.headers`` shall be populated.
"""
env = self.server.get_environ()
env['REQUEST_METHOD'] = self.command
env['SCRIPT_NAME'] = ''
if '?' in self.path:
path, query = self.path.split('?', 1)
else:
path, query = self.path, ''
# Note that self.path contains the original str object; if it contains
# encoded escapes, it will NOT match PATH_INFO.
env['PATH_INFO'] = unquote_latin1(path)
env['QUERY_STRING'] = query
if self.headers.typeheader is not None:
env['CONTENT_TYPE'] = self.headers.typeheader
length = self.headers.getheader('content-length')
if length:
env['CONTENT_LENGTH'] = length
env['SERVER_PROTOCOL'] = self.request_version
client_address = self.client_address
if isinstance(client_address, tuple):
env['REMOTE_ADDR'] = str(client_address[0])
env['REMOTE_PORT'] = str(client_address[1])
for key, value in self._headers():
if key in env:
if 'COOKIE' in key:
env[key] += '; ' + value
else:
env[key] += ',' + value
else:
env[key] = value
if env.get('HTTP_EXPECT') == '100-continue':
socket = self.socket
else:
socket = None
chunked = env.get('HTTP_TRANSFER_ENCODING', '').lower() == 'chunked'
self.wsgi_input = Input(self.rfile, self.content_length, socket=socket, chunked_input=chunked)
env['wsgi.input'] = self.wsgi_input
return env
|
Construct and return a new WSGI environment dictionary for a specific request.
This should begin with asking the server for the base environment
using :meth:`WSGIServer.get_environ`, and then proceed to add the
request specific values.
By the time this method is invoked the request line and request shall have
been parsed and ``self.headers`` shall be populated.
|
get_environ
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pywsgi.py
|
MIT
|
def __init__(self, logger, level=20):
"""
Write information to the *logger* at the given *level* (default to INFO).
"""
self._logger = logger
self._level = level
|
Write information to the *logger* at the given *level* (default to INFO).
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pywsgi.py
|
MIT
|
def update_environ(self):
"""
Called before the first request is handled to fill in WSGI environment values.
This includes getting the correct server name and port.
"""
address = self.address
if isinstance(address, tuple):
if 'SERVER_NAME' not in self.environ:
try:
name = socket.getfqdn(address[0])
except socket.error:
name = str(address[0])
if PY3 and not isinstance(name, str):
name = name.decode('ascii')
self.environ['SERVER_NAME'] = name
self.environ.setdefault('SERVER_PORT', str(address[1]))
else:
self.environ.setdefault('SERVER_NAME', '')
self.environ.setdefault('SERVER_PORT', '')
|
Called before the first request is handled to fill in WSGI environment values.
This includes getting the correct server name and port.
|
update_environ
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/pywsgi.py
|
MIT
|
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional arg *block* is true and *timeout* is ``None`` (the default),
block if necessary until a free slot is available. If *timeout* is
a positive number, it blocks at most *timeout* seconds and raises
the :class:`Full` exception if no free slot was available within that time.
Otherwise (*block* is false), put an item on the queue if a free slot
is immediately available, else raise the :class:`Full` exception (*timeout*
is ignored in that case).
"""
if self.maxsize is None or self.qsize() < self.maxsize:
# there's a free slot, put an item right away
self._put(item)
if self.getters:
self._schedule_unlock()
elif self.hub is getcurrent():
# We're in the mainloop, so we cannot wait; we can switch to other greenlets though.
# Check if possible to get a free slot in the queue.
while self.getters and self.qsize() and self.qsize() >= self.maxsize:
getter = self.getters.popleft()
getter.switch(getter)
if self.qsize() < self.maxsize:
self._put(item)
return
raise Full
elif block:
waiter = ItemWaiter(item, self)
self.putters.append(waiter)
timeout = Timeout._start_new_or_dummy(timeout, Full)
try:
if self.getters:
self._schedule_unlock()
result = waiter.get()
if result is not waiter:
raise InvalidSwitchError("Invalid switch into Queue.put: %r" % (result, ))
finally:
timeout.cancel()
_safe_remove(self.putters, waiter)
else:
raise Full
|
Put an item into the queue.
If optional arg *block* is true and *timeout* is ``None`` (the default),
block if necessary until a free slot is available. If *timeout* is
a positive number, it blocks at most *timeout* seconds and raises
the :class:`Full` exception if no free slot was available within that time.
Otherwise (*block* is false), put an item on the queue if a free slot
is immediately available, else raise the :class:`Full` exception (*timeout*
is ignored in that case).
|
put
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/queue.py
|
MIT
|
def get(self, block=True, timeout=None):
"""Remove and return an item from the queue.
If optional args *block* is true and *timeout* is ``None`` (the default),
block if necessary until an item is available. If *timeout* is a positive number,
it blocks at most *timeout* seconds and raises the :class:`Empty` exception
if no item was available within that time. Otherwise (*block* is false), return
an item if one is immediately available, else raise the :class:`Empty` exception
(*timeout* is ignored in that case).
"""
if self.qsize():
if self.putters:
self._schedule_unlock()
return self._get()
return self.__get_or_peek(self._get, block, timeout)
|
Remove and return an item from the queue.
If optional args *block* is true and *timeout* is ``None`` (the default),
block if necessary until an item is available. If *timeout* is a positive number,
it blocks at most *timeout* seconds and raises the :class:`Empty` exception
if no item was available within that time. Otherwise (*block* is false), return
an item if one is immediately available, else raise the :class:`Empty` exception
(*timeout* is ignored in that case).
|
get
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/queue.py
|
MIT
|
def peek(self, block=True, timeout=None):
"""Return an item from the queue without removing it.
If optional args *block* is true and *timeout* is ``None`` (the default),
block if necessary until an item is available. If *timeout* is a positive number,
it blocks at most *timeout* seconds and raises the :class:`Empty` exception
if no item was available within that time. Otherwise (*block* is false), return
an item if one is immediately available, else raise the :class:`Empty` exception
(*timeout* is ignored in that case).
"""
if self.qsize():
# XXX: Why doesn't this schedule an unlock like get() does?
return self._peek()
return self.__get_or_peek(self._peek, block, timeout)
|
Return an item from the queue without removing it.
If optional args *block* is true and *timeout* is ``None`` (the default),
block if necessary until an item is available. If *timeout* is a positive number,
it blocks at most *timeout* seconds and raises the :class:`Empty` exception
if no item was available within that time. Otherwise (*block* is false), return
an item if one is immediately available, else raise the :class:`Empty` exception
(*timeout* is ignored in that case).
|
peek
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/queue.py
|
MIT
|
def __init__(self, maxsize=None, items=None, unfinished_tasks=None):
"""
.. versionchanged:: 1.1a1
If *unfinished_tasks* is not given, then all the given *items*
(if any) will be considered unfinished.
"""
from gevent.event import Event
Queue.__init__(self, maxsize, items)
self._cond = Event()
self._cond.set()
if unfinished_tasks:
self.unfinished_tasks = unfinished_tasks
elif items:
self.unfinished_tasks = len(items)
else:
self.unfinished_tasks = 0
if self.unfinished_tasks:
self._cond.clear()
|
.. versionchanged:: 1.1a1
If *unfinished_tasks* is not given, then all the given *items*
(if any) will be considered unfinished.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/queue.py
|
MIT
|
def task_done(self):
'''Indicate that a formerly enqueued task is complete. Used by queue consumer threads.
For each :meth:`get <Queue.get>` used to fetch a task, a subsequent call to :meth:`task_done` tells the queue
that the processing on the task is complete.
If a :meth:`join` is currently blocking, it will resume when all items have been processed
(meaning that a :meth:`task_done` call was received for every item that had been
:meth:`put <Queue.put>` into the queue).
Raises a :exc:`ValueError` if called more times than there were items placed in the queue.
'''
if self.unfinished_tasks <= 0:
raise ValueError('task_done() called too many times')
self.unfinished_tasks -= 1
if self.unfinished_tasks == 0:
self._cond.set()
|
Indicate that a formerly enqueued task is complete. Used by queue consumer threads.
For each :meth:`get <Queue.get>` used to fetch a task, a subsequent call to :meth:`task_done` tells the queue
that the processing on the task is complete.
If a :meth:`join` is currently blocking, it will resume when all items have been processed
(meaning that a :meth:`task_done` call was received for every item that had been
:meth:`put <Queue.put>` into the queue).
Raises a :exc:`ValueError` if called more times than there were items placed in the queue.
|
task_done
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/queue.py
|
MIT
|
def select(rlist, wlist, xlist, timeout=None):
"""An implementation of :meth:`select.select` that blocks only the current greenlet.
Note: *xlist* is ignored.
"""
watchers = []
loop = get_hub().loop
io = loop.io
MAXPRI = loop.MAXPRI
result = SelectResult()
try:
try:
for readfd in rlist:
watcher = io(get_fileno(readfd), 1)
watcher.priority = MAXPRI
watcher.start(result.add_read, readfd)
watchers.append(watcher)
for writefd in wlist:
watcher = io(get_fileno(writefd), 2)
watcher.priority = MAXPRI
watcher.start(result.add_write, writefd)
watchers.append(watcher)
except IOError as ex:
raise error(*ex.args)
result.event.wait(timeout=timeout)
return result.read, result.write, []
finally:
for watcher in watchers:
watcher.stop()
|
An implementation of :meth:`select.select` that blocks only the current greenlet.
Note: *xlist* is ignored.
|
select
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/select.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/select.py
|
MIT
|
def _tcp_listener(address, backlog=50, reuse_addr=None, family=_socket.AF_INET):
"""A shortcut to create a TCP socket, bind it and put it into listening state."""
sock = socket(family=family)
if reuse_addr is not None:
sock.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, reuse_addr)
try:
sock.bind(address)
except _socket.error as ex:
strerror = getattr(ex, 'strerror', None)
if strerror is not None:
ex.strerror = strerror + ': ' + repr(address)
raise
sock.listen(backlog)
sock.setblocking(0)
return sock
|
A shortcut to create a TCP socket, bind it and put it into listening state.
|
_tcp_listener
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/server.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/server.py
|
MIT
|
def getsignal(signalnum):
"""
Exactly the same as :func:`signal.signal` except where
:const:`signal.SIGCHLD` is concerned.
"""
if signalnum != _signal.SIGCHLD:
return _signal_getsignal(signalnum)
global _child_handler
if _child_handler is _INITIAL:
_child_handler = _signal_getsignal(_signal.SIGCHLD)
return _child_handler
|
Exactly the same as :func:`signal.signal` except where
:const:`signal.SIGCHLD` is concerned.
|
getsignal
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/signal.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/signal.py
|
MIT
|
def signal(signalnum, handler):
"""
Exactly the same as :func:`signal.signal` except where
:const:`signal.SIGCHLD` is concerned.
.. note::
A :const:`signal.SIGCHLD` handler installed with this function
will only be triggered for children that are forked using
:func:`gevent.os.fork` (:func:`gevent.os.fork_and_watch`);
children forked before monkey patching, or otherwise by the raw
:func:`os.fork`, will not trigger the handler installed by this
function. (It's unlikely that a SIGCHLD handler installed with
the builtin :func:`signal.signal` would be triggered either;
libev typically overwrites such a handler at the C level. At
the very least, it's full of race conditions.)
.. note::
Use of ``SIG_IGN`` and ``SIG_DFL`` may also have race conditions
with libev child watchers and the :mod:`gevent.subprocess` module.
.. versionchanged:: 1.1rc2
Allow using ``SIG_IGN`` and ``SIG_DFL`` to reset and ignore ``SIGCHLD``.
However, this allows the possibility of a race condition.
"""
if signalnum != _signal.SIGCHLD:
return _signal_signal(signalnum, handler)
# TODO: raise value error if not called from the main
# greenlet, just like threads
if handler != _signal.SIG_IGN and handler != _signal.SIG_DFL and not callable(handler):
# exact same error message raised by the stdlib
raise TypeError("signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object")
old_handler = getsignal(signalnum)
global _child_handler
_child_handler = handler
if handler == _signal.SIG_IGN or handler == _signal.SIG_DFL:
# Allow resetting/ignoring this signal at the process level.
# Note that this conflicts with gevent.subprocess and other users
# of child watchers.
_signal_signal(signalnum, handler)
return old_handler
|
Exactly the same as :func:`signal.signal` except where
:const:`signal.SIGCHLD` is concerned.
.. note::
A :const:`signal.SIGCHLD` handler installed with this function
will only be triggered for children that are forked using
:func:`gevent.os.fork` (:func:`gevent.os.fork_and_watch`);
children forked before monkey patching, or otherwise by the raw
:func:`os.fork`, will not trigger the handler installed by this
function. (It's unlikely that a SIGCHLD handler installed with
the builtin :func:`signal.signal` would be triggered either;
libev typically overwrites such a handler at the C level. At
the very least, it's full of race conditions.)
.. note::
Use of ``SIG_IGN`` and ``SIG_DFL`` may also have race conditions
with libev child watchers and the :mod:`gevent.subprocess` module.
.. versionchanged:: 1.1rc2
Allow using ``SIG_IGN`` and ``SIG_DFL`` to reset and ignore ``SIGCHLD``.
However, this allows the possibility of a race condition.
|
signal
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/signal.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/signal.py
|
MIT
|
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None):
"""Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
A host of '' or port 0 tells the OS to use the default.
"""
host, port = address
err = None
for res in getaddrinfo(host, port, 0 if has_ipv6 else AF_INET, SOCK_STREAM):
af, socktype, proto, _canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
return sock
except error as ex:
# without exc_clear(), if connect() fails once, the socket is referenced by the frame in exc_info
# and the next bind() fails (see test__socket.TestCreateConnection)
# that does not happen with regular sockets though, because _socket.socket.connect() is a built-in.
# this is similar to "getnameinfo loses a reference" failure in test_socket.py
if not PY3:
sys.exc_clear()
if sock is not None:
sock.close()
err = ex
if err is not None:
raise err
else:
raise error("getaddrinfo returns an empty list")
|
Connect to *address* and return the socket object.
Convenience function. Connect to *address* (a 2-tuple ``(host,
port)``) and return the socket object. Passing the optional
*timeout* parameter will set the timeout on the socket instance
before attempting to connect. If no *timeout* is supplied, the
global default timeout setting returned by :func:`getdefaulttimeout`
is used. If *source_address* is set it must be a tuple of (host, port)
for the socket to bind as a source address before making the connection.
A host of '' or port 0 tells the OS to use the default.
|
create_connection
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/win32/gevent/socket.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/win32/gevent/socket.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.