我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用eventlet.monkey_patch()。
def run(self, handler): from eventlet import wsgi, listen, patcher if not patcher.is_monkey_patched(os): msg = "Bottle requires eventlet.monkey_patch() (before import)" raise RuntimeError(msg) socket_args = {} for arg in ('backlog', 'family'): try: socket_args[arg] = self.options.pop(arg) except KeyError: pass address = (self.host, self.port) try: wsgi.server(listen(address, **socket_args), handler, log_output=(not self.quiet)) except TypeError: # Fallback, if we have old version of eventlet wsgi.server(listen(address), handler)
def run(servername, ip, port, softcron=True, logging=False, profiler=None, options=None): if servername == 'gevent': from gevent import monkey monkey.patch_all() elif servername == 'eventlet': import eventlet eventlet.monkey_patch() import gluon.main if logging: application = gluon.main.appfactory(wsgiapp=gluon.main.wsgibase, logfilename='httpserver.log', profiler_dir=profiler) else: application = gluon.main.wsgibase if softcron: from gluon.settings import global_settings global_settings.web2py_crontype = 'soft' getattr(Servers, servername)(application, (ip, int(port)), options=options)
def monkey_patch(): """Greening the world (eventlet) The approach is to monkeypatch the Standard Library. For more details see http://eventlet.net/doc/patching.html """ if os.name == 'nt': # eventlet monkey patching the os and thread modules causes # subprocess.Popen to fail on Windows when using pipes due # to missing non-blocking IO support. # # bug report on eventlet: # https://bitbucket.org/eventlet/eventlet/issue/132/ # eventletmonkey_patch-breaks eventlet.monkey_patch(os=False, thread=False) else: eventlet.monkey_patch()
def setup(url=None, optional=False): """Initialise the oslo_messaging layer.""" global TRANSPORT, NOTIFIER if url and url.startswith("fake://"): # NOTE(sileht): oslo_messaging fake driver uses time.sleep # for task switch, so we need to monkey_patch it eventlet.monkey_patch(time=True) if not TRANSPORT: oslo_messaging.set_transport_defaults('bilean') exmods = ['bilean.common.exception'] try: TRANSPORT = oslo_messaging.get_transport( cfg.CONF, url, allowed_remote_exmods=exmods) except oslo_messaging.InvalidTransportURL as e: TRANSPORT = None if not optional or e.url: # NOTE(sileht): oslo_messaging is configured but unloadable # so reraise the exception raise if not NOTIFIER and TRANSPORT: serializer = RequestContextSerializer(JsonPayloadSerializer()) NOTIFIER = oslo_messaging.Notifier(TRANSPORT, serializer=serializer)
def main(): mode = config.get("CENO", "agent") if mode == "client": import eventlet import eventlet.wsgi eventlet.monkey_patch() bm_api.setup() api_ok = testapi() if not api_ok: logger.critical("Failed to test Bitmessage API, is it properly configured and running?") return if mode == "server": launch_server() elif mode == "client": launch_client(eventlet, eventlet.wsgi) else: logger.critical("Unknown agent mode") return
def __call__(self, app, host, port, use_debugger, use_reloader): # override the default runserver command to start a Socket.IO server if use_debugger is None: use_debugger = app.debug if use_debugger is None: use_debugger = True if use_reloader is None: use_reloader = app.debug import eventlet # monkey_patch eventlet.monkey_patch() socketio.run(app, host=host, port=port, debug=use_debugger, use_reloader=use_reloader, **self.server_options)
def main(): eventlet.monkey_patch() cfg.CONF(project='neutron') logging_config.setup_logging(cfg.CONF) try: interface_mappings = q_utils.parse_mappings( cfg.CONF.LINUX_BRIDGE.physical_interface_mappings) except ValueError as e: LOG.error(_("Parsing physical_interface_mappings failed: %s." " Agent terminated!"), e) sys.exit(1) LOG.info(_("Interface mappings: %s"), interface_mappings) polling_interval = cfg.CONF.AGENT.polling_interval root_helper = cfg.CONF.AGENT.root_helper agent = CalicoNeutronAgentRPC(interface_mappings, polling_interval, root_helper) LOG.info(_("Agent initialized successfully, now running... ")) agent.daemon_loop() sys.exit(0)
def test_simple(self): new_mod = """ import eventlet from eventlet import patcher patcher.monkey_patch() from eventlet import tpool print("newmod {0}".format(tpool.execute(len, "hi"))) print("newmod {0}".format(tpool.execute(len, "hi2"))) tpool.killall() """ self.write_to_tempfile("newmod", new_mod) output, lines = self.launch_subprocess('newmod.py') self.assertEqual(len(lines), 3, output) assert lines[0].startswith('newmod'), repr(output) assert '2' in lines[0], repr(output) assert '3' in lines[1], repr(output)
def test_threading(self): new_mod = """import eventlet eventlet.monkey_patch() import threading def test(): print(repr(threading.currentThread())) t = threading.Thread(target=test) t.start() t.join() print(len(threading._active)) """ self.write_to_tempfile("newmod", new_mod) output, lines = self.launch_subprocess('newmod.py') self.assertEqual(len(lines), 3, "\n".join(lines)) assert lines[0].startswith('<_MainThread'), lines[0] self.assertEqual(lines[1], "1", lines[1])
def test_greenlet(self): new_mod = """import eventlet eventlet.monkey_patch() from eventlet import event import threading evt = event.Event() def test(): print(repr(threading.currentThread())) evt.send() eventlet.spawn_n(test) evt.wait() print(len(threading._active)) """ self.write_to_tempfile("newmod", new_mod) output, lines = self.launch_subprocess('newmod.py') self.assertEqual(len(lines), 3, "\n".join(lines)) assert lines[0].startswith('<_MainThread'), lines[0] self.assertEqual(lines[1], "1", lines[1])
def main(): config.parse_args(sys.argv) utils.monkey_patch() _session = session.XenAPISession(CONF.xenserver.connection_url, CONF.xenserver.connection_username, CONF.xenserver.connection_password) sr_ref = vm_utils.safe_find_sr(_session) destroyed = vm_utils.destroy_cached_images( _session, sr_ref, all_cached=CONF.all_cached, dry_run=CONF.dry_run) if '--verbose' in sys.argv: print '\n'.join(destroyed) print "Destroyed %d cached VDIs" % len(destroyed)
def _cli_patch(cli_args): # pragma: no coverage parsed_args, _ = _cli_parse(cli_args) opts = parsed_args if opts.server: if opts.server.startswith('gevent'): import gevent.monkey gevent.monkey.patch_all() elif opts.server.startswith('eventlet'): import eventlet eventlet.monkey_patch()
def initialize_reactor(cls): eventlet.monkey_patch() if not cls._timers: cls._timers = TimerManager() cls._timeout_watcher = eventlet.spawn(cls.service_timeouts) cls._new_timer = Event()
def main(): try: eventlet.monkey_patch(os=False) # the configuration will be into the cfg.CONF global data structure config.parseArgs(args=sys.argv[1:], default_config_files=["/etc/synergy/synergy.conf"]) if not cfg.CONF.config_file: sys.exit("ERROR: Unable to find configuration file via the " "default search paths (~/.synergy/, ~/, /etc/synergy/" ", /etc/) and the '--config-file' option!") setLogger(name="synergy") setLogger(name="oslo.messaging._drivers") global LOG LOG = logging.getLogger(__name__) LOG.info("Starting Synergy...") server = Synergy() server.start() LOG.info("Synergy started") except Exception as ex: LOG.error("unrecoverable error: %s" % ex)
def main(): log.register_options(CONF) CONF(sys.argv[1:], project='meteos', version=version.version_string()) log.setup(CONF, "meteos") utils.monkey_patch() launcher = service.process_launcher() server = service.WSGIService('osapi_learning') launcher.launch_service(server, workers=server.workers or 1) launcher.wait()
def _cli_patch(args): opts, _, _ = _cli_parse(args) if opts.server: if opts.server.startswith('gevent'): import gevent.monkey gevent.monkey.patch_all() elif opts.server.startswith('eventlet'): import eventlet eventlet.monkey_patch()
def patch(self): hubs.use_hub() eventlet.monkey_patch(os=False) patch_sendfile()