How to use the gevent.monkey.patch_all function in gevent

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 unthingable / Agentum / agentum / runner.py View on Github external
start_response('404 NOT FOUND', [('Content-Type', 'text/plain')])
                    return ['Not Found']

        ws_server = pywsgi.WSGIServer(
            ('', 9990), app,
            handler_class=WebSocketHandler)
        # http server: serves up static files
        # http_server = gevent.pywsgi.WSGIServer(
        #     ('', 8000),
        #     paste.urlparser.StaticURLParser(os.path.dirname(__file__)))
        print "Connect to http://localhost:9990/"
        ws_server.serve_forever()

    elif args.telnet:
        import gevent
        from gevent import monkey; monkey.patch_all()
        from gevent.server import StreamServer
        gevent.signal(signal.SIGQUIT, dbhandler)
        gevent.signal(signal.SIGTERM, gevent.shutdown)
        gevent.signal(signal.SIGHUP, gevent.shutdown)

        def handle(socket, address):
            log.debug("Connected: %s" % str(address))
            socket.send("Welcome to simulation server\n")

            def push(obj):
                socket.send("%s\n" % obj)
            protocol.push = push

            worker = load_sim(simmodule)
            fileobj = socket.makefile()
github playay / ws2s / ws2s / tcp_sockets.py View on Github external
import sys
import base64
import logging
logger = logging.getLogger(__name__)

import gevent
from gevent import socket
from gevent import monkey
monkey.patch_all()

from sshtunnel import SSHTunnelForwarder

from ws2s import ws2s_config


_tcp_sockets = {}
_tcp_socket_handlers = {}

_ssh_tunnels = {}

class FailedToOpenSSHTunnel(Exception):
    code = 6
    message = "Failed To Open SSH Tunnel. socketId: {}"

    def __init__(self, socket_id):
github spmjs / yuan / manager.py View on Github external
# coding: utf-8

import os
import sys
import gevent.monkey
gevent.monkey.patch_all()

from flask.ext.script import Manager
from yuan.app import create_app
from yuan.models import Project, Package
from flask import json

ROOTDIR = os.path.abspath(os.path.dirname(__file__))
CONF = os.path.join(ROOTDIR, 'etc/config.py')
if not os.path.exists(CONF):
    CONF = os.path.join(ROOTDIR, 'conf/dev_config.py')

app = create_app(CONF)
manager = Manager(app)


@manager.command
github mozilla / mozillians / vendor-local / lib / python / celery / concurrency / gevent.py View on Github external
# -*- coding: utf-8 -*-
from __future__ import absolute_import

import os
if not os.environ.get("GEVENT_NOPATCH"):
    from gevent import monkey
    monkey.patch_all()

import sys

from time import time

from ..utils import timer2

from .base import apply_target, BasePool


class Schedule(timer2.Schedule):

    def __init__(self, *args, **kwargs):
        from gevent.greenlet import Greenlet, GreenletExit

        class _Greenlet(Greenlet):
github Lujeni / Surcharge / surcharge / surcharge.py View on Github external
#/usr/bin/env python
# -*- coding: utf-8 -*-

from gevent import monkey
monkey.patch_all()

import time
import requests
import argparse
import gevent
import os
import sys
import urlparse

from gevent.pool import Pool
from gevent.socket import gethostbyname
from gevent.dns import DNSError
from collections import defaultdict
from sys import exit
github Germey / ProxyFilter / proxyfilter / grequests.py View on Github external
This module contains an asynchronous replica of ``requests.api``, powered
by gevent. All API methods return a ``Request`` instance (as opposed to
``Response``). A list of requests can be sent with ``map()``.
"""
from functools import partial
import traceback
try:
    import gevent
    from gevent import monkey as curious_george
    from gevent.pool import Pool
except ImportError:
    raise RuntimeError('Gevent is required for grequests.')

# Monkey-patch.
curious_george.patch_all(thread=False, select=False)

from requests import Session


__all__ = (
    'map', 'imap',
    'get', 'options', 'head', 'post', 'put', 'patch', 'delete', 'request'
)


class AsyncRequest(object):
    """ Asynchronous request.

    Accept same parameters as ``Session.request`` and some additional:

    :param session: Session which will do request
github EDSM-NET / EDDN / src / eddn / Gateway.py View on Github external
import hashlib
import logging
import simplejson
import urlparse
import zlib
import zmq.green as zmq
from datetime import datetime

from pkg_resources import resource_string
# import os

from eddn.conf.Settings import Settings, loadConfig
from eddn.core.Validator import Validator, ValidationSeverity

from gevent import monkey
monkey.patch_all()
from bottle import Bottle, run, request, response, get, post
app = Bottle()

logger = logging.getLogger(__name__)

# This socket is used to push market data out to the Announcers over ZeroMQ.
context = zmq.Context()
sender = context.socket(zmq.PUB)

validator = Validator()

# This import must be done post-monkey-patching!
from eddn.core.StatsCollector import StatsCollector
statsCollector = StatsCollector()
statsCollector.start()