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 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/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/greenlet.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/hub.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/hub.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/osx64/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/monkey.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/os.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/pywsgi.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/queue.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/select.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/server.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/signal.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/signal.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/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/osx64/gevent/socket.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/socket.py
|
MIT
|
def call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = call(["ls", "-l"])
"""
timeout = kwargs.pop('timeout', None)
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout)
except:
p.kill()
p.wait()
raise
|
Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = call(["ls", "-l"])
|
call
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def check_call(*popenargs, **kwargs):
"""Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
:exc:`CalledProcessError`. The ``CalledProcessError`` object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = check_call(["ls", "-l"])
"""
retcode = call(*popenargs, **kwargs)
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd)
return 0
|
Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
:exc:`CalledProcessError`. The ``CalledProcessError`` object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = check_call(["ls", "-l"])
|
check_call
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output.
If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
``CalledProcessError`` object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-1", "/dev/null"])
b'/dev/null\n'
The ``stdout`` argument is not allowed as it is used internally.
To capture standard error in the result, use ``stderr=STDOUT``::
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
b'ls: non_existent_file: No such file or directory\n'
There is an additional optional argument, "input", allowing you to
pass a string to the subprocess's stdin. If you use this argument
you may not also use the Popen constructor's "stdin" argument, as
it too will be used internally. Example::
>>> check_output(["sed", "-e", "s/foo/bar/"],
... input=b"when in the course of fooman events\n")
b'when in the course of barman events\n'
If ``universal_newlines=True`` is passed, the return value will be a
string rather than bytes.
"""
timeout = kwargs.pop('timeout', None)
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
if 'input' in kwargs:
if 'stdin' in kwargs:
raise ValueError('stdin and input arguments may not both be used.')
inputdata = kwargs['input']
del kwargs['input']
kwargs['stdin'] = PIPE
else:
inputdata = None
with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
try:
output, unused_err = process.communicate(inputdata, timeout=timeout)
except TimeoutExpired:
process.kill()
output, unused_err = process.communicate()
raise TimeoutExpired(process.args, timeout, output=output)
except:
process.kill()
process.wait()
raise
retcode = process.poll()
if retcode:
raise CalledProcessError(retcode, process.args, output=output)
return output
|
Run command with arguments and return its output.
If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
``CalledProcessError`` object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-1", "/dev/null"])
b'/dev/null\n'
The ``stdout`` argument is not allowed as it is used internally.
To capture standard error in the result, use ``stderr=STDOUT``::
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
b'ls: non_existent_file: No such file or directory\n'
There is an additional optional argument, "input", allowing you to
pass a string to the subprocess's stdin. If you use this argument
you may not also use the Popen constructor's "stdin" argument, as
it too will be used internally. Example::
>>> check_output(["sed", "-e", "s/foo/bar/"],
... input=b"when in the course of fooman events\n")
b'when in the course of barman events\n'
If ``universal_newlines=True`` is passed, the return value will be a
string rather than bytes.
|
check_output
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> print(check_output(["ls", "-1", "/dev/null"]).decode('ascii'))
/dev/null
<BLANKLINE>
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> print(check_output(["/bin/sh", "-c", "echo hello world"], stderr=STDOUT).decode('ascii'))
hello world
<BLANKLINE>
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output = process.communicate()[0]
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
ex = CalledProcessError(retcode, cmd)
# on Python 2.6 and older CalledProcessError does not accept 'output' argument
ex.output = output
raise ex
return output
|
Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> print(check_output(["ls", "-1", "/dev/null"]).decode('ascii'))
/dev/null
<BLANKLINE>
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> print(check_output(["/bin/sh", "-c", "echo hello world"], stderr=STDOUT).decode('ascii'))
hello world
<BLANKLINE>
|
check_output
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def __init__(self, args, bufsize=None, executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, shell=False,
cwd=None, env=None, universal_newlines=False,
startupinfo=None, creationflags=0, threadpool=None,
**kwargs):
"""Create new Popen instance.
:param kwargs: *Only* allowed under Python 3; under Python 2, any
unrecognized keyword arguments will result in a :exc:`TypeError`.
Under Python 3, keyword arguments can include ``pass_fds``, ``start_new_session``,
and ``restore_signals``.
"""
if not PY3 and kwargs:
raise TypeError("Got unexpected keyword arguments", kwargs)
pass_fds = kwargs.pop('pass_fds', ())
start_new_session = kwargs.pop('start_new_session', False)
restore_signals = kwargs.pop('restore_signals', True)
hub = get_hub()
if bufsize is None:
# bufsize has different defaults on Py3 and Py2
if PY3:
bufsize = -1
else:
bufsize = 0
if not isinstance(bufsize, integer_types):
raise TypeError("bufsize must be an integer")
if mswindows:
if preexec_fn is not None:
raise ValueError("preexec_fn is not supported on Windows "
"platforms")
any_stdio_set = (stdin is not None or stdout is not None or
stderr is not None)
if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
if any_stdio_set:
close_fds = False
else:
close_fds = True
elif close_fds and any_stdio_set:
raise ValueError("close_fds is not supported on Windows "
"platforms if you redirect stdin/stdout/stderr")
if threadpool is None:
threadpool = hub.threadpool
self.threadpool = threadpool
self._waiting = False
else:
# POSIX
if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
# close_fds has different defaults on Py3/Py2
if PY3:
close_fds = True
else:
close_fds = False
if pass_fds and not close_fds:
import warnings
warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
close_fds = True
if startupinfo is not None:
raise ValueError("startupinfo is only supported on Windows "
"platforms")
if creationflags != 0:
raise ValueError("creationflags is only supported on Windows "
"platforms")
assert threadpool is None
self._loop = hub.loop
if PY3:
self.args = args
self.stdin = None
self.stdout = None
self.stderr = None
self.pid = None
self.returncode = None
self.universal_newlines = universal_newlines
self.result = AsyncResult()
# Input and output objects. The general principle is like
# this:
#
# Parent Child
# ------ -----
# p2cwrite ---stdin---> p2cread
# c2pread <--stdout--- c2pwrite
# errread <--stderr--- errwrite
#
# On POSIX, the child objects are file descriptors. On
# Windows, these are Windows file handles. The parent objects
# are file descriptors on both platforms. The parent objects
# are None when not using PIPEs. The child objects are None
# when not redirecting.
(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
# We wrap OS handles *before* launching the child, otherwise a
# quickly terminating child could make our fds unwrappable
# (see #8458).
if mswindows:
if p2cwrite is not None:
p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
if c2pread is not None:
c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
if errread is not None:
errread = msvcrt.open_osfhandle(errread.Detach(), 0)
if p2cwrite is not None:
if PY3 and universal_newlines:
# Under Python 3, if we left on the 'b' we'd get different results
# depending on whether we used FileObjectPosix or FileObjectThread
self.stdin = FileObject(p2cwrite, 'wb', bufsize)
self.stdin._translate = True
self.stdin.io = io.TextIOWrapper(self.stdin.io, write_through=True,
line_buffering=(bufsize == 1))
else:
self.stdin = FileObject(p2cwrite, 'wb', bufsize)
if c2pread is not None:
if universal_newlines:
if PY3:
# FileObjectThread doesn't support the 'U' qualifier
# with a bufsize of 0
self.stdout = FileObject(c2pread, 'rb', bufsize)
# NOTE: Universal Newlines are broken on Windows/Py3, at least
# in some cases. This is true in the stdlib subprocess module
# as well; the following line would fix the test cases in
# test__subprocess.py that depend on python_universal_newlines,
# but would be inconsistent with the stdlib:
#msvcrt.setmode(self.stdout.fileno(), os.O_TEXT)
self.stdout.io = io.TextIOWrapper(self.stdout.io)
self.stdout.io.mode = 'r'
self.stdout._translate = True
else:
self.stdout = FileObject(c2pread, 'rU', bufsize)
else:
self.stdout = FileObject(c2pread, 'rb', bufsize)
if errread is not None:
if universal_newlines:
if PY3:
self.stderr = FileObject(errread, 'rb', bufsize)
self.stderr.io = io.TextIOWrapper(self.stderr.io)
self.stderr._translate = True
else:
self.stderr = FileObject(errread, 'rU', bufsize)
else:
self.stderr = FileObject(errread, 'rb', bufsize)
self._closed_child_pipe_fds = False
try:
self._execute_child(args, executable, preexec_fn, close_fds,
pass_fds, cwd, env, universal_newlines,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
restore_signals, start_new_session)
except:
# Cleanup if the child failed starting.
# (gevent: New in python3, but reported as gevent bug in #347.
# Note that under Py2, any error raised below will replace the
# original error so we have to use reraise)
if not PY3:
exc_info = sys.exc_info()
for f in filter(None, (self.stdin, self.stdout, self.stderr)):
try:
f.close()
except (OSError, IOError):
pass # Ignore EBADF or other errors.
if not self._closed_child_pipe_fds:
to_close = []
if stdin == PIPE:
to_close.append(p2cread)
if stdout == PIPE:
to_close.append(c2pwrite)
if stderr == PIPE:
to_close.append(errwrite)
if hasattr(self, '_devnull'):
to_close.append(self._devnull)
for fd in to_close:
try:
os.close(fd)
except (OSError, IOError):
pass
if not PY3:
try:
reraise(*exc_info)
finally:
del exc_info
raise
|
Create new Popen instance.
:param kwargs: *Only* allowed under Python 3; under Python 2, any
unrecognized keyword arguments will result in a :exc:`TypeError`.
Under Python 3, keyword arguments can include ``pass_fds``, ``start_new_session``,
and ``restore_signals``.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def communicate(self, input=None, timeout=None):
"""Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.
communicate() returns a tuple (stdout, stderr).
:keyword timeout: Under Python 2, this is a gevent extension; if
given and it expires, we will raise :class:`gevent.timeout.Timeout`.
Under Python 3, this raises the standard :exc:`TimeoutExpired` exception.
.. versionchanged:: 1.1a2
Under Python 2, if the *timeout* elapses, raise the :exc:`gevent.timeout.Timeout`
exception. Previously, we silently returned.
.. versionchanged:: 1.1b5
Honor a *timeout* even if there's no way to communicate with the child
(stdin, stdout, and stderr are not pipes).
"""
greenlets = []
if self.stdin:
greenlets.append(spawn(write_and_close, self.stdin, input))
# If the timeout parameter is used, and the caller calls back after
# getting a TimeoutExpired exception, we can wind up with multiple
# greenlets trying to run and read from and close stdout/stderr.
# That's bad because it can lead to 'RuntimeError: reentrant call in io.BufferedReader'.
# We can't just kill the previous greenlets when a timeout happens,
# though, because we risk losing the output collected by that greenlet
# (and Python 3, where timeout is an official parameter, explicitly says
# that no output should be lost in the event of a timeout.) Instead, we're
# watching for the exception and ignoring it. It's not elegant,
# but it works
if self.stdout:
def _read_out():
try:
data = self.stdout.read()
except RuntimeError:
return
if self._stdout_buffer is not None:
self._stdout_buffer += data
else:
self._stdout_buffer = data
stdout = spawn(_read_out)
greenlets.append(stdout)
else:
stdout = None
if self.stderr:
def _read_err():
try:
data = self.stderr.read()
except RuntimeError:
return
if self._stderr_buffer is not None:
self._stderr_buffer += data
else:
self._stderr_buffer = data
stderr = spawn(_read_err)
greenlets.append(stderr)
else:
stderr = None
# If we were given stdin=stdout=stderr=None, we have no way to
# communicate with the child, and thus no greenlets to wait
# on. This is a nonsense case, but it comes up in the test
# case for Python 3.5 (test_subprocess.py
# RunFuncTestCase.test_timeout). Instead, we go directly to
# self.wait
if not greenlets and timeout is not None:
result = self.wait(timeout=timeout)
# Python 3 would have already raised, but Python 2 would not
# so we need to do that manually
if result is None:
from gevent.timeout import Timeout
raise Timeout(timeout)
done = joinall(greenlets, timeout=timeout)
if timeout is not None and len(done) != len(greenlets):
if PY3:
raise TimeoutExpired(self.args, timeout)
from gevent.timeout import Timeout
raise Timeout(timeout)
if self.stdout:
try:
self.stdout.close()
except RuntimeError:
pass
if self.stderr:
try:
self.stderr.close()
except RuntimeError:
pass
self.wait()
stdout_value = self._stdout_buffer
self._stdout_buffer = None
stderr_value = self._stderr_buffer
self._stderr_buffer = None
# XXX: Under python 3 in universal newlines mode we should be
# returning str, not bytes
return (None if stdout is None else stdout_value or b'',
None if stderr is None else stderr_value or b'')
|
Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.
communicate() returns a tuple (stdout, stderr).
:keyword timeout: Under Python 2, this is a gevent extension; if
given and it expires, we will raise :class:`gevent.timeout.Timeout`.
Under Python 3, this raises the standard :exc:`TimeoutExpired` exception.
.. versionchanged:: 1.1a2
Under Python 2, if the *timeout* elapses, raise the :exc:`gevent.timeout.Timeout`
exception. Previously, we silently returned.
.. versionchanged:: 1.1b5
Honor a *timeout* even if there's no way to communicate with the child
(stdin, stdout, and stderr are not pipes).
|
communicate
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def _find_w9xpopen(self):
"""Find and return absolute path to w9xpopen.exe"""
w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
"w9xpopen.exe")
if not os.path.exists(w9xpopen):
# Eeek - file-not-found - possibly an embedding
# situation - see if we can locate it in sys.exec_prefix
w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
"w9xpopen.exe")
if not os.path.exists(w9xpopen):
raise RuntimeError("Cannot locate w9xpopen.exe, which is "
"needed for Popen to work with your "
"shell or platform.")
return w9xpopen
|
Find and return absolute path to w9xpopen.exe
|
_find_w9xpopen
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def _internal_poll(self):
"""Check if child process has terminated. Returns returncode
attribute.
"""
if self.returncode is None:
if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
self.returncode = GetExitCodeProcess(self._handle)
self.result.set(self.returncode)
return self.returncode
|
Check if child process has terminated. Returns returncode
attribute.
|
_internal_poll
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def pipe_cloexec(self):
"""Create a pipe with FDs set CLOEXEC."""
# Pipes' FDs are set CLOEXEC by default because we don't want them
# to be inherited by other subprocesses: the CLOEXEC flag is removed
# from the child's FDs by _dup2(), between fork() and exec().
# This is not atomic: we would need the pipe2() syscall for that.
r, w = os.pipe()
self._set_cloexec_flag(r)
self._set_cloexec_flag(w)
return r, w
|
Create a pipe with FDs set CLOEXEC.
|
pipe_cloexec
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def wait(self, timeout=None):
"""Wait for child process to terminate. Returns :attr:`returncode`
attribute.
:keyword timeout: The floating point number of seconds to wait.
Under Python 2, this is a gevent extension, and we simply return if it
expires. Under Python 3,
if this time elapses without finishing the process, :exc:`TimeoutExpired`
is raised."""
result = self.result.wait(timeout=timeout)
if PY3 and timeout is not None and not self.result.ready():
raise TimeoutExpired(self.args, timeout)
return result
|
Wait for child process to terminate. Returns :attr:`returncode`
attribute.
:keyword timeout: The floating point number of seconds to wait.
Under Python 2, this is a gevent extension, and we simply return if it
expires. Under Python 3,
if this time elapses without finishing the process, :exc:`TimeoutExpired`
is raised.
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/subprocess.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/subprocess.py
|
MIT
|
def join(self):
"""Waits until all outstanding tasks have been completed."""
delay = 0.0005
while self.task_queue.unfinished_tasks > 0:
sleep(delay)
delay = min(delay * 2, .05)
|
Waits until all outstanding tasks have been completed.
|
join
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/threadpool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/threadpool.py
|
MIT
|
def spawn(self, func, *args, **kwargs):
"""
Add a new task to the threadpool that will run ``func(*args, **kwargs)``.
Waits until a slot is available. Creates a new thread if necessary.
:return: A :class:`gevent.event.AsyncResult`.
"""
while True:
semaphore = self._semaphore
semaphore.acquire()
if semaphore is self._semaphore:
break
thread_result = None
try:
task_queue = self.task_queue
result = AsyncResult()
# XXX We're calling the semaphore release function in the hub, otherwise
# we get LoopExit (why?). Previously it was done with a rawlink on the
# AsyncResult and the comment that it is "competing for order with get(); this is not
# good, just make ThreadResult release the semaphore before doing anything else"
thread_result = ThreadResult(result, hub=self.hub, call_when_ready=semaphore.release)
task_queue.put((func, args, kwargs, thread_result))
self.adjust()
except:
if thread_result is not None:
thread_result.destroy()
semaphore.release()
raise
return result
|
Add a new task to the threadpool that will run ``func(*args, **kwargs)``.
Waits until a slot is available. Creates a new thread if necessary.
:return: A :class:`gevent.event.AsyncResult`.
|
spawn
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/threadpool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/threadpool.py
|
MIT
|
def apply_e(self, expected_errors, function, args=None, kwargs=None):
"""
.. deprecated:: 1.1a2
Identical to :meth:`apply`; the ``expected_errors`` argument is ignored.
"""
# Deprecated but never documented. In the past, before
# self.apply() allowed all errors to be raised to the caller,
# expected_errors allowed a caller to specify a set of errors
# they wanted to be raised, through the wrap_errors function.
# In practice, it always took the value Exception or
# BaseException.
return self.apply(function, args, kwargs)
|
.. deprecated:: 1.1a2
Identical to :meth:`apply`; the ``expected_errors`` argument is ignored.
|
apply_e
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/threadpool.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/threadpool.py
|
MIT
|
def start_new(cls, timeout=None, exception=None, ref=True):
"""Create a started :class:`Timeout`.
This is a shortcut, the exact action depends on *timeout*'s type:
* If *timeout* is a :class:`Timeout`, then call its :meth:`start` method
if it's not already begun.
* Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as
arguments, then call its :meth:`start` method.
Returns the :class:`Timeout` instance.
"""
if isinstance(timeout, Timeout):
if not timeout.pending:
timeout.start()
return timeout
timeout = cls(timeout, exception, ref=ref)
timeout.start()
return timeout
|
Create a started :class:`Timeout`.
This is a shortcut, the exact action depends on *timeout*'s type:
* If *timeout* is a :class:`Timeout`, then call its :meth:`start` method
if it's not already begun.
* Otherwise, create a new :class:`Timeout` instance, passing (*timeout*, *exception*) as
arguments, then call its :meth:`start` method.
Returns the :class:`Timeout` instance.
|
start_new
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/timeout.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/timeout.py
|
MIT
|
def __str__(self):
"""
>>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Timeout
"""
if self.seconds is None:
return ''
suffix = '' if self.seconds == 1 else 's'
if self.exception is None:
return '%s second%s' % (self.seconds, suffix)
if self.exception is False:
return '%s second%s (silent)' % (self.seconds, suffix)
return '%s second%s: %s' % (self.seconds, suffix, self.exception)
|
>>> raise Timeout #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
Timeout
|
__str__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/timeout.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/timeout.py
|
MIT
|
def with_timeout(seconds, function, *args, **kwds):
"""Wrap a call to *function* with a timeout; if the called
function fails to return before the timeout, cancel it and return a
flag value, provided by *timeout_value* keyword argument.
If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`.
Keyword argument *timeout_value* is not passed to *function*.
"""
timeout_value = kwds.pop("timeout_value", _NONE)
timeout = Timeout.start_new(seconds)
try:
try:
return function(*args, **kwds)
except Timeout as ex:
if ex is timeout and timeout_value is not _NONE:
return timeout_value
raise
finally:
timeout.cancel()
|
Wrap a call to *function* with a timeout; if the called
function fails to return before the timeout, cancel it and return a
flag value, provided by *timeout_value* keyword argument.
If timeout expires but *timeout_value* is not provided, raise :class:`Timeout`.
Keyword argument *timeout_value* is not passed to *function*.
|
with_timeout
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/timeout.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/timeout.py
|
MIT
|
def __init__(self, errors, func):
"""
Calling this makes a new function from *func*, such that it catches *errors* (an
:exc:`BaseException` subclass, or a tuple of :exc:`BaseException` subclasses) and
return it as a value.
"""
self.__errors = errors
self.__func = func
# Set __doc__, __wrapped__, etc, especially useful on Python 3.
functools.update_wrapper(self, func)
|
Calling this makes a new function from *func*, such that it catches *errors* (an
:exc:`BaseException` subclass, or a tuple of :exc:`BaseException` subclasses) and
return it as a value.
|
__init__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/util.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/util.py
|
MIT
|
def release(self):
"""
Release the semaphore, notifying any waiters if needed.
"""
self.counter += 1
self._start_notify()
return self.counter
|
Release the semaphore, notifying any waiters if needed.
|
release
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def rawlink(self, callback):
"""
rawlink(callback) -> None
Register a callback to call when a counter is more than zero.
*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.
This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most code
will not need to use it.
"""
if not callable(callback):
raise TypeError('Expected callable:', callback)
if self._links is None:
self._links = [callback]
else:
self._links.append(callback)
self._dirty = True
|
rawlink(callback) -> None
Register a callback to call when a counter is more than zero.
*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.
This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most code
will not need to use it.
|
rawlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def unlink(self, callback):
"""
unlink(callback) -> None
Remove the callback set by :meth:`rawlink`.
This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most
code will not need to use it.
"""
try:
self._links.remove(callback)
self._dirty = True
except (ValueError, AttributeError):
pass
if not self._links:
self._links = None
# TODO: Cancel a notifier if there are no links?
|
unlink(callback) -> None
Remove the callback set by :meth:`rawlink`.
This method is normally called automatically by :meth:`acquire` and :meth:`wait`; most
code will not need to use it.
|
unlink
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def _do_wait(self, timeout):
"""
Wait for up to *timeout* seconds to expire. If timeout
elapses, return the exception. Otherwise, return None.
Raises timeout if a different timer expires.
"""
switch = getcurrent().switch
self.rawlink(switch)
try:
timer = Timeout._start_new_or_dummy(timeout)
try:
try:
result = get_hub().switch()
assert result is self, 'Invalid switch into Semaphore.wait/acquire(): %r' % (result, )
except Timeout as ex:
if ex is not timer:
raise
return ex
finally:
timer.cancel()
finally:
self.unlink(switch)
|
Wait for up to *timeout* seconds to expire. If timeout
elapses, return the exception. Otherwise, return None.
Raises timeout if a different timer expires.
|
_do_wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def wait(self, timeout=None):
"""
wait(timeout=None) -> int
Wait until it is possible to acquire this semaphore, or until the optional
*timeout* elapses.
.. caution:: If this semaphore was initialized with a size of 0,
this method will block forever if no timeout is given.
:keyword float timeout: If given, specifies the maximum amount of seconds
this method will block.
:return: A number indicating how many times the semaphore can be acquired
before blocking.
"""
if self.counter > 0:
return self.counter
self._do_wait(timeout) # return value irrelevant, whether we got it or got a timeout
return self.counter
|
wait(timeout=None) -> int
Wait until it is possible to acquire this semaphore, or until the optional
*timeout* elapses.
.. caution:: If this semaphore was initialized with a size of 0,
this method will block forever if no timeout is given.
:keyword float timeout: If given, specifies the maximum amount of seconds
this method will block.
:return: A number indicating how many times the semaphore can be acquired
before blocking.
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def acquire(self, blocking=True, timeout=None):
"""
acquire(blocking=True, timeout=None) -> bool
Acquire the semaphore.
.. caution:: If this semaphore was initialized with a size of 0,
this method will block forever (unless a timeout is given or blocking is
set to false).
:keyword bool blocking: If True (the default), this function will block
until the semaphore is acquired.
:keyword float timeout: If given, specifies the maximum amount of seconds
this method will block.
:return: A boolean indicating whether the semaphore was acquired.
If ``blocking`` is True and ``timeout`` is None (the default), then
(so long as this semaphore was initialized with a size greater than 0)
this will always return True. If a timeout was given, and it expired before
the semaphore was acquired, False will be returned. (Note that this can still
raise a ``Timeout`` exception, if some other caller had already started a timer.)
"""
if self.counter > 0:
self.counter -= 1
return True
if not blocking:
return False
timeout = self._do_wait(timeout)
if timeout is not None:
# Our timer expired.
return False
# Neither our timer no another one expired, so we blocked until
# awoke. Therefore, the counter is ours
self.counter -= 1
assert self.counter >= 0
return True
|
acquire(blocking=True, timeout=None) -> bool
Acquire the semaphore.
.. caution:: If this semaphore was initialized with a size of 0,
this method will block forever (unless a timeout is given or blocking is
set to false).
:keyword bool blocking: If True (the default), this function will block
until the semaphore is acquired.
:keyword float timeout: If given, specifies the maximum amount of seconds
this method will block.
:return: A boolean indicating whether the semaphore was acquired.
If ``blocking`` is True and ``timeout`` is None (the default), then
(so long as this semaphore was initialized with a size greater than 0)
this will always return True. If a timeout was given, and it expired before
the semaphore was acquired, False will be returned. (Note that this can still
raise a ``Timeout`` exception, if some other caller had already started a timer.)
|
acquire
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_semaphore.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_semaphore.py
|
MIT
|
def _wait(self, watcher, timeout_exc=timeout('timed out')):
"""Block the current greenlet until *watcher* has pending events.
If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
By default *timeout_exc* is ``socket.timeout('timed out')``.
If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
"""
if watcher.callback is not None:
raise _socketcommon.ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (watcher.callback, ))
if self.timeout is not None:
timeout = Timeout.start_new(self.timeout, timeout_exc, ref=False)
else:
timeout = None
try:
self.hub.wait(watcher)
finally:
if timeout is not None:
timeout.cancel()
|
Block the current greenlet until *watcher* has pending events.
If *timeout* is non-negative, then *timeout_exc* is raised after *timeout* second has passed.
By default *timeout_exc* is ``socket.timeout('timed out')``.
If :func:`cancel_wait` is called, raise ``socket.error(EBADF, 'File descriptor was closed in another greenlet')``.
|
_wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket2.py
|
MIT
|
def __send_chunk(self, data_memory, flags, timeleft, end):
"""
Send the complete contents of ``data_memory`` before returning.
This is the core loop around :meth:`send`.
:param timeleft: Either ``None`` if there is no timeout involved,
or a float indicating the timeout to use.
:param end: Either ``None`` if there is no timeout involved, or
a float giving the absolute end time.
:return: An updated value for ``timeleft`` (or None)
:raises timeout: If ``timeleft`` was given and elapsed while
sending this chunk.
"""
data_sent = 0
len_data_memory = len(data_memory)
started_timer = 0
while data_sent < len_data_memory:
chunk = data_memory[data_sent:]
if timeleft is None:
data_sent += self.send(chunk, flags)
elif started_timer and timeleft <= 0:
# Check before sending to guarantee a check
# happens even if each chunk successfully sends its data
# (especially important for SSL sockets since they have large
# buffers)
raise timeout('timed out')
else:
started_timer = 1
data_sent += self.send(chunk, flags, timeout=timeleft)
timeleft = end - time.time()
return timeleft
|
Send the complete contents of ``data_memory`` before returning.
This is the core loop around :meth:`send`.
:param timeleft: Either ``None`` if there is no timeout involved,
or a float indicating the timeout to use.
:param end: Either ``None`` if there is no timeout involved, or
a float giving the absolute end time.
:return: An updated value for ``timeleft`` (or None)
:raises timeout: If ``timeleft`` was given and elapsed while
sending this chunk.
|
__send_chunk
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket2.py
|
MIT
|
def __repr__(self):
"""Wrap __repr__() to reveal the real class name."""
try:
s = _socket.socket.__repr__(self._sock)
except Exception as ex:
# Observed on Windows Py3.3, printing the repr of a socket
# that just sufferred a ConnectionResetError [WinError 10054]:
# "OverflowError: no printf formatter to display the socket descriptor in decimal"
# Not sure what the actual cause is or if there's a better way to handle this
s = '<socket [%r]>' % ex
if s.startswith("<socket object"):
s = "<%s.%s%s%s" % (self.__class__.__module__,
self.__class__.__name__,
getattr(self, '_closed', False) and " [closed] " or "",
s[7:])
return s
|
Wrap __repr__() to reveal the real class name.
|
__repr__
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def dup(self):
"""dup() -> socket object
Return a new socket object connected to the same system resource.
"""
fd = dup(self.fileno())
sock = self.__class__(self.family, self.type, self.proto, fileno=fd)
sock.settimeout(self.gettimeout())
return sock
|
dup() -> socket object
Return a new socket object connected to the same system resource.
|
dup
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def makefile(self, mode="r", buffering=None, *,
encoding=None, errors=None, newline=None):
"""Return an I/O stream connected to the socket
The arguments are as for io.open() after the filename,
except the only mode characters supported are 'r', 'w' and 'b'.
The semantics are similar too.
"""
# (XXX refactor to share code?)
for c in mode:
if c not in {"r", "w", "b"}:
raise ValueError("invalid mode %r (only r, w, b allowed)")
writing = "w" in mode
reading = "r" in mode or not writing
assert reading or writing
binary = "b" in mode
rawmode = ""
if reading:
rawmode += "r"
if writing:
rawmode += "w"
raw = SocketIO(self, rawmode)
self._io_refs += 1
if buffering is None:
buffering = -1
if buffering < 0:
buffering = io.DEFAULT_BUFFER_SIZE
if buffering == 0:
if not binary:
raise ValueError("unbuffered streams must be binary")
return raw
if reading and writing:
buffer = io.BufferedRWPair(raw, raw, buffering)
elif reading:
buffer = io.BufferedReader(raw, buffering)
else:
assert writing
buffer = io.BufferedWriter(raw, buffering)
if binary:
return buffer
text = io.TextIOWrapper(buffer, encoding, errors, newline)
text.mode = mode
return text
|
Return an I/O stream connected to the socket
The arguments are as for io.open() after the filename,
except the only mode characters supported are 'r', 'w' and 'b'.
The semantics are similar too.
|
makefile
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socket3.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socket3.py
|
MIT
|
def wait(io, timeout=None, timeout_exc=_NONE):
"""
Block the current greenlet until *io* is ready.
If *timeout* is non-negative, then *timeout_exc* is raised after
*timeout* second has passed. By default *timeout_exc* is
``socket.timeout('timed out')``.
If :func:`cancel_wait` is called on *io* by another greenlet,
raise an exception in this blocking greenlet
(``socket.error(EBADF, 'File descriptor was closed in another
greenlet')`` by default).
:param io: A libev watcher, most commonly an IO watcher obtained from
:meth:`gevent.core.loop.io`
:keyword timeout_exc: The exception to raise if the timeout expires.
By default, a :class:`socket.timeout` exception is raised.
If you pass a value for this keyword, it is interpreted as for
:class:`gevent.timeout.Timeout`.
"""
if io.callback is not None:
raise ConcurrentObjectUseError('This socket is already used by another greenlet: %r' % (io.callback, ))
if timeout is not None:
timeout_exc = timeout_exc if timeout_exc is not _NONE else _timeout_error('timed out')
timeout = Timeout.start_new(timeout, timeout_exc)
try:
return get_hub().wait(io)
finally:
if timeout is not None:
timeout.cancel()
# rename "io" to "watcher" because wait() works with any watcher
|
Block the current greenlet until *io* is ready.
If *timeout* is non-negative, then *timeout_exc* is raised after
*timeout* second has passed. By default *timeout_exc* is
``socket.timeout('timed out')``.
If :func:`cancel_wait` is called on *io* by another greenlet,
raise an exception in this blocking greenlet
(``socket.error(EBADF, 'File descriptor was closed in another
greenlet')`` by default).
:param io: A libev watcher, most commonly an IO watcher obtained from
:meth:`gevent.core.loop.io`
:keyword timeout_exc: The exception to raise if the timeout expires.
By default, a :class:`socket.timeout` exception is raised.
If you pass a value for this keyword, it is interpreted as for
:class:`gevent.timeout.Timeout`.
|
wait
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def wait_read(fileno, timeout=None, timeout_exc=_NONE):
"""
Block the current greenlet until *fileno* is ready to read.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
.. seealso:: :func:`cancel_wait`
"""
io = get_hub().loop.io(fileno, 1)
return wait(io, timeout, timeout_exc)
|
Block the current greenlet until *fileno* is ready to read.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
.. seealso:: :func:`cancel_wait`
|
wait_read
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def wait_write(fileno, timeout=None, timeout_exc=_NONE, event=_NONE):
"""
Block the current greenlet until *fileno* is ready to write.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
:keyword event: Ignored. Applications should not pass this parameter.
In the future, it may become an error.
.. seealso:: :func:`cancel_wait`
"""
io = get_hub().loop.io(fileno, 2)
return wait(io, timeout, timeout_exc)
|
Block the current greenlet until *fileno* is ready to write.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
:keyword event: Ignored. Applications should not pass this parameter.
In the future, it may become an error.
.. seealso:: :func:`cancel_wait`
|
wait_write
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def wait_readwrite(fileno, timeout=None, timeout_exc=_NONE, event=_NONE):
"""
Block the current greenlet until *fileno* is ready to read or
write.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
:keyword event: Ignored. Applications should not pass this parameter.
In the future, it may become an error.
.. seealso:: :func:`cancel_wait`
"""
io = get_hub().loop.io(fileno, 3)
return wait(io, timeout, timeout_exc)
|
Block the current greenlet until *fileno* is ready to read or
write.
For the meaning of the other parameters and possible exceptions,
see :func:`wait`.
:keyword event: Ignored. Applications should not pass this parameter.
In the future, it may become an error.
.. seealso:: :func:`cancel_wait`
|
wait_readwrite
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_socketcommon.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_socketcommon.py
|
MIT
|
def connect(self, addr):
"""Connects to remote ADDR, and then wraps the connection in
an SSL channel."""
# Here we assume that the socket is client-side, and not
# connected at the time of the call. We connect it, then wrap it.
if self._sslobj:
raise ValueError("attempt to connect already-connected SSLSocket!")
socket.connect(self, addr)
if self.ciphers is None:
self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
self.cert_reqs, self.ssl_version,
self.ca_certs)
else:
self._sslobj = _ssl.sslwrap(self._sock, False, self.keyfile, self.certfile,
self.cert_reqs, self.ssl_version,
self.ca_certs, self.ciphers)
if self.do_handshake_on_connect:
self.do_handshake()
|
Connects to remote ADDR, and then wraps the connection in
an SSL channel.
|
connect
|
python
|
mchristopher/PokemonGo-DesktopMap
|
app/pylibs/osx64/gevent/_ssl2.py
|
https://github.com/mchristopher/PokemonGo-DesktopMap/blob/master/app/pylibs/osx64/gevent/_ssl2.py
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.