How to use gevent - 10 common examples

To help you get started, we’ve selected a few gevent examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github gevent / gevent / greentest / test__issue6.py View on Github external
if not sys.argv[1:]:
    from subprocess import Popen, PIPE
    p = Popen([sys.executable, __file__, 'subprocess'], stdin=PIPE, stdout=PIPE, stderr=PIPE)
    out, err = p.communicate(b'hello world\n')
    code = p.poll()
    assert p.poll() == 0, (out, err, code)
    assert out.strip() == b'11 chars.', (out, err, code)
    # XXX: This is seen sometimes to fail on Travis with the following value in err but a code of 0;
    # it seems load related:
    #  'Unhandled exception in thread started by \nsys.excepthook is missing\nlost sys.stderr\n'
    assert err == b'', (out, err, code)

elif sys.argv[1:] == ['subprocess']:
    import gevent
    import gevent.monkey
    gevent.monkey.patch_all(sys=True)

    def printline():
        try:
            line = raw_input()
        except NameError:
            line = input()
        print('%s chars.' % len(line))

    gevent.spawn(printline).join()

else:
    sys.exit('Invalid arguments: %r' % (sys.argv, ))
github ceph / s3-tests / s3tests / common / greenlets.py View on Github external
import time

from ..common import context, get_next_key
from ..common.results import TransferGreenletResult
from ..realistic import FileVerifier


# Make sure context has somewhere to store what we need
context.update(bunch.Bunch(
    needs_first_read=collections.deque(),
    all_keys=[],
    files_iter=None,
))


class SafeTransferGreenlet(gevent.Greenlet):
    def __init__(self, timeout=120):
        gevent.Greenlet.__init__(self)
        self.timeout = timeout
        self.result = None

    def _run(self):
        result = self.result = TransferGreenletResult(self.type)
        result.markStarted()

        try:
            with gevent.Timeout(self.timeout, False):
                result.success = self._doit()
        except gevent.GreenletExit:
            return
        except:
            result.setError(show_traceback=True)
github decentfox / tulipcore / greentest / test__socket_dns.py View on Github external
def wait(self, timeout):
        with gevent.Timeout(timeout, False):
            for index in range(1000000):
                try:
                    gevent_socket.gethostbyname('www.x%s.com' % index)
                except socket.error:
                    pass
            raise AssertionError('Timeout was not raised')
github gevent / gevent / greentest / test_hub_join_timeout.py View on Github external
# exiting because of timeout (the spawned greenlet still runs)
    for _ in xrange(2):
        x = gevent.spawn_later(10, lambda: 5)
        with expected_time(SMALL):
            result = gevent.wait(timeout=SMALL)
        assert result is False, repr(result)
        assert not x.dead, (x, x._start_event)
        x.kill()
        with no_time():
            result = gevent.wait()
        assert result is True

    # exiting because of event (the spawned greenlet still runs)
    for _ in xrange(2):
        x = gevent.spawn_later(10, lambda: 5)
        event = Event()
        event_set = gevent.spawn_later(SMALL, event.set)
        with expected_time(SMALL):
            result = gevent.wait([event])
        assert result == [event], repr(result)
        assert not x.dead, x
        assert event_set.dead
        assert event.is_set()
        x.kill()
        with no_time():
            result = gevent.wait()
        assert result is True

    # checking "ref=False" argument
    for _ in xrange(2):
        gevent.get_hub().loop.timer(10, ref=False).start(lambda: None)
github gevent / gevent / greentest / test__greenlet.py View on Github external
def _test_kill_running(self, block):
        link_test = []
        g = gevent.spawn(gevent.sleep, 10)
        g.link(lambda x: link_test.append(x))
        self._test_kill(g, block=block)
        gevent.sleep(0.01)
        assert link_test == [g]
github gevent / gevent / greentest / test__api.py View on Github external
def test_timer_fired(self):
        lst = [1]

        def func():
            gevent.spawn_later(0.01, lst.pop)
            gevent.sleep(0.02)

        gevent.spawn(func)
        assert lst == [1], lst
        gevent.sleep(0.03)
        assert lst == [], lst
github initc3 / HoneyBadgerBFT-Python / test / honest_party_test_Bitmessage_broadcast.py View on Github external
def Listener():
            while True:
                gevent.sleep(SLEEP_TIME)
                msgs = json.loads(api_Read[i].getAllInboxMessages())['inboxMessages']
                for msg in msgs:
                    receipt_no = i
                    tmpvar = base64.b64decode(msg['message'])
                    if tmpvar[:3] == 'HB-':
                        result = decode(
                            base64.b64decode(
                                tmpvar[3:]
                            )
                        )
                        if result:
                            mylog('[%d] got message %s' % (receipt_no, result))
                            recvChannel[receipt_no].put((
                                address.index(msg['fromAddress']), result
                            ))
                    api_Read[i].trashMessage(msg['msgid'])
github jgehrcke / gipc / test / test_gipc.py View on Github external
def test_lock_out_of_context_pair_2(self):
        with raises(GIPCLocked):
            with pipe(True) as (h1, h2):
                gr = gevent.spawn(lambda h: h.get(), h2)
                gevent.sleep(SHORTTIME)
                # Context succeeds closing h1 reader and writer. Fails during
                # closing h2 reader.
        assert not h2._reader._closed
        assert h1._reader._closed
        assert h2._writer._closed
        assert h1._writer._closed
        gr.kill(block=False)
        gevent.sleep(-1)
        h2.close()
github gevent / gevent / greentest / test__core_fork.py View on Github external
def run(q):
    # libev only calls fork callbacks at the beginning of
    # the loop; we use callbacks extensively so it takes *two*
    # calls to sleep (with a timer) to actually get wrapped
    # around to the beginning of the loop.
    gevent.sleep(0.01)
    gevent.sleep(0.01)
    q.put(newpid)
github 0rpc / zerorpc-python / tests / test_buffered_channel.py View on Github external
server = zerorpc.ChannelMultiplexer(server_events)

    client_events = zerorpc.Events(zmq.DEALER)
    client_events.connect(endpoint)
    client = zerorpc.ChannelMultiplexer(client_events, ignore_broadcast=True)

    client_channel = client.channel()
    client_hbchan = zerorpc.HeartBeatOnChannel(client_channel, freq=TIME_FACTOR * 2)
    client_bufchan = zerorpc.BufferedChannel(client_hbchan)

    event = server.recv()
    server_channel = server.channel(event)
    server_hbchan = zerorpc.HeartBeatOnChannel(server_channel, freq=TIME_FACTOR * 2)
    server_bufchan = zerorpc.BufferedChannel(server_hbchan)

    gevent.sleep(TIME_FACTOR * 3)
    print('CLOSE SERVER SOCKET!!!')
    server_bufchan.close()
    if sys.version_info < (2, 7):
        assert_raises(zerorpc.LostRemote, client_bufchan.recv)
    else:
        with assert_raises(zerorpc.LostRemote):
            client_bufchan.recv()
    print('CLIENT LOST SERVER :)')
    client_bufchan.close()
    server.close()
    client.close()