Python greenlet.getcurrent() Examples

The following are 30 code examples of greenlet.getcurrent(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module greenlet , or try the search function .
Example #1
Source File: iterio.py    From scylla with Apache License 2.0 6 votes vote down vote up
def __new__(cls, func, sentinel=""):
        if greenlet is None:
            raise RuntimeError("IterI requires greenlet support")
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #2
Source File: iterio.py    From pyRevit with GNU General Public License v3.0 6 votes vote down vote up
def __new__(cls, func, sentinel=''):
        if greenlet is None:
            raise RuntimeError('IterI requires greenlet support')
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #3
Source File: eventlet_backdoor.py    From oslo.service with Apache License 2.0 6 votes vote down vote up
def _capture_profile(fname=''):
    if not fname:
        yappi.set_clock_type('cpu')
        # We need to set context to greenlet to profile greenlets
        # https://bitbucket.org/sumerc/yappi/pull-requests/3
        yappi.set_context_id_callback(
            lambda: id(greenlet.getcurrent()))
        yappi.set_context_name_callback(
            lambda: greenlet.getcurrent().__class__.__name__)
        yappi.start()
    else:
        yappi.stop()
        stats = yappi.get_func_stats()
        # User should provide filename. This file with a suffix .prof
        # will be created in temp directory.
        try:
            stats_file = os.path.join(tempfile.gettempdir(), fname + '.prof')
            stats.save(stats_file, "pstat")
        except Exception as e:
            print("Error while saving the trace stats ", str(e))
        finally:
            yappi.clear_stats() 
Example #4
Source File: iterio.py    From jbox with MIT License 6 votes vote down vote up
def __new__(cls, func, sentinel=''):
        if greenlet is None:
            raise RuntimeError('IterI requires greenlet support')
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #5
Source File: hub.py    From PhonePi_SampleServer with MIT License 6 votes vote down vote up
def handle_system_error(self, type, value):
        current = getcurrent()
        if current is self or current is self.parent or self.loop is None:
            self.parent.throw(type, value)
        else:
            # in case system error was handled and life goes on
            # switch back to this greenlet as well
            cb = None
            try:
                cb = self.loop.run_callback(current.switch)
            except: # pylint:disable=bare-except
                traceback.print_exc(file=self.exception_stream)
            try:
                self.parent.throw(type, value)
            finally:
                if cb is not None:
                    cb.stop() 
Example #6
Source File: hub.py    From PhonePi_SampleServer with MIT License 6 votes vote down vote up
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() 
Example #7
Source File: connections.py    From TorMySQL with MIT License 6 votes vote down vote up
def wrap_socket(self, sock, server_side=False,
                    do_handshake_on_connect=True,
                    suppress_ragged_eofs=True,
                    server_hostname=None, session=None):

        child_gr = greenlet.getcurrent()
        main = child_gr.parent
        assert main is not None, "Execut must be running in child greenlet"

        def finish(future):
            if (hasattr(future, "_exc_info") and future._exc_info is not None) \
                    or (hasattr(future, "_exception") and future._exception is not None):
                child_gr.throw(future.exception())
            else:
                child_gr.switch(future.result())

        future = sock.start_tls(False, self._ctx, server_hostname=server_hostname, connect_timeout=self._connection.connect_timeout)
        future.add_done_callback(finish)
        return main.switch() 
Example #8
Source File: green.py    From greentor with MIT License 6 votes vote down vote up
def synclize(func):
    coro = coroutine(func)

    @wraps(func)
    def _sync_call(*args, **kwargs):
        child_gr = greenlet.getcurrent()
        main = child_gr.parent
        assert main, "only run in child greenlet"

        def callback(future):
            if future.exc_info():
                child_gr.throw(*future.exc_info())
            elif future.exception():
                child_gr.throw(future.exception())
            else:
                child_gr.switch(future.result())

        IOLoop.current().add_future(coro(*args, **kwargs), callback)
        return main.switch()

    return _sync_call 
Example #9
Source File: iterio.py    From planespotter with MIT License 6 votes vote down vote up
def __new__(cls, func, sentinel=''):
        if greenlet is None:
            raise RuntimeError('IterI requires greenlet support')
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #10
Source File: iterio.py    From lambda-packs with MIT License 6 votes vote down vote up
def __new__(cls, func, sentinel=''):
        if greenlet is None:
            raise RuntimeError('IterI requires greenlet support')
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #11
Source File: hub.py    From satori with Apache License 2.0 6 votes vote down vote up
def handle_system_error(self, type, value):
        current = getcurrent()
        if current is self or current is self.parent or self.loop is None:
            self.parent.throw(type, value)
        else:
            # in case system error was handled and life goes on
            # switch back to this greenlet as well
            cb = None
            try:
                cb = self.loop.run_callback(current.switch)
            except:
                traceback.print_exc()
            try:
                self.parent.throw(type, value)
            finally:
                if cb is not None:
                    cb.stop() 
Example #12
Source File: iterio.py    From Financial-Portfolio-Flask with MIT License 6 votes vote down vote up
def __new__(cls, func, sentinel=''):
        if greenlet is None:
            raise RuntimeError('IterI requires greenlet support')
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #13
Source File: hub.py    From satori with Apache License 2.0 6 votes vote down vote up
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() 
Example #14
Source File: hub.py    From satori with Apache License 2.0 6 votes vote down vote up
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 
Example #15
Source File: core.py    From vanilla with MIT License 6 votes vote down vote up
def sleep(self, ms=1):
        """
        Pauses the current green thread for *ms* milliseconds::

            p = h.pipe()

            @h.spawn
            def _():
                p.send('1')
                h.sleep(50)
                p.send('2')

            p.recv() # returns '1'
            p.recv() # returns '2' after 50 ms
        """
        self.scheduled.add(ms, getcurrent())
        self.loop.switch() 
Example #16
Source File: iterio.py    From Building-Recommendation-Systems-with-Python with MIT License 6 votes vote down vote up
def __new__(cls, func, sentinel=""):
        if greenlet is None:
            raise RuntimeError("IterI requires greenlet support")
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #17
Source File: core.py    From vanilla with MIT License 6 votes vote down vote up
def pause(self, timeout=-1):
        if timeout > -1:
            item = self.scheduled.add(
                timeout,
                getcurrent(),
                vanilla.exception.Timeout('timeout: %s' % timeout))

        assert getcurrent() != self.loop, "cannot pause the main loop"

        resume = None
        try:
            resume = self.loop.switch()
        finally:
            if timeout > -1:
                if isinstance(resume, vanilla.exception.Timeout):
                    raise resume
                # since we didn't timeout, remove ourselves from scheduled
                self.scheduled.remove(item)

        # TODO: rework State's is set test to be more natural
        if self.stopped.recver.ready:
            raise vanilla.exception.Stop(
                'Hub stopped while we were paused. There must be a deadlock.')

        return resume 
Example #18
Source File: iterio.py    From RSSNewsGAE with Apache License 2.0 6 votes vote down vote up
def __new__(cls, func, sentinel=''):
        if greenlet is None:
            raise RuntimeError('IterI requires greenlet support')
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #19
Source File: iterio.py    From Flask-P2P with MIT License 6 votes vote down vote up
def __new__(cls, func, sentinel=''):
        if greenlet is None:
            raise RuntimeError('IterI requires greenlet support')
        stream = object.__new__(cls)
        stream._parent = greenlet.getcurrent()
        stream._buffer = []
        stream.closed = False
        stream.sentinel = sentinel
        stream.pos = 0

        def run():
            func(stream)
            stream.close()

        g = greenlet.greenlet(run, stream._parent)
        while 1:
            rv = g.switch()
            if not rv:
                return
            yield rv[0] 
Example #20
Source File: local.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        object.__setattr__(self, '__storage__', {})
        object.__setattr__(self, '__ident_func__', get_ident) 
Example #21
Source File: local.py    From Financial-Portfolio-Flask with MIT License 5 votes vote down vote up
def get_ident(self):
        """Return the context identifier the local objects use internally for
        this context.  You cannot override this method to change the behavior
        but use it to link other context local objects (such as SQLAlchemy's
        scoped sessions) to the Werkzeug locals.

        .. versionchanged:: 0.7
           You can pass a different ident function to the local manager that
           will then be propagated to all the locals passed to the
           constructor.
        """
        return self.ident_func() 
Example #22
Source File: hub.py    From PhonePi_SampleServer with MIT License 5 votes vote down vote up
def switch(self):
        switch_out = getattr(getcurrent(), 'switch_out', None)
        if switch_out is not None:
            switch_out()
        return RawGreenlet.switch(self) 
Example #23
Source File: local.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def get_ident(self):
        """Return the context identifier the local objects use internally for
        this context.  You cannot override this method to change the behavior
        but use it to link other context local objects (such as SQLAlchemy's
        scoped sessions) to the Werkzeug locals.

        .. versionchanged:: 0.7
           You can pass a different ident function to the local manager that
           will then be propagated to all the locals passed to the
           constructor.
        """
        return self.ident_func() 
Example #24
Source File: core.py    From vanilla with MIT License 5 votes vote down vote up
def switch_to(self, target, *a):
        self.ready.append((getcurrent(), ()))
        return target.switch(*a) 
Example #25
Source File: message.py    From vanilla with MIT License 5 votes vote down vote up
def select(self):
        assert self.current is None
        self.current = getcurrent() 
Example #26
Source File: message.py    From vanilla with MIT License 5 votes vote down vote up
def select(self):
            assert getcurrent() not in self.current
            self.current.append(getcurrent()) 
Example #27
Source File: message.py    From vanilla with MIT License 5 votes vote down vote up
def unselect(self):
            self.current.remove(getcurrent()) 
Example #28
Source File: message.py    From vanilla with MIT License 5 votes vote down vote up
def select(self):
            assert getcurrent() not in self.current
            self.current.append(getcurrent()) 
Example #29
Source File: message.py    From vanilla with MIT License 5 votes vote down vote up
def unselect(self):
            self.current.remove(getcurrent()) 
Example #30
Source File: base_camera.py    From flask-video-streaming with MIT License 5 votes vote down vote up
def clear(self):
        """Invoked from each client's thread after a frame was processed."""
        self.events[get_ident()][0].clear()