我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.internet.reactor.addSystemEventTrigger()。
def apply_script(protocol, connection, config): class MapSaveProtocol(protocol): def __init__(self, *arg, **kw): protocol.__init__(self, *arg, **kw) reactor.addSystemEventTrigger('before', 'shutdown', self.save_map) def get_map(self, name): map = protocol.get_map(self, name) if config.get('load_saved_map', False): cached_path = get_name(map) if os.path.isfile(cached_path): map.data = VXLData(open(cached_path, 'rb')) return map def save_map(self): open(get_name(self.map_info), 'wb').write(self.map.generate()) return MapSaveProtocol, connection
def configure(protocol, port, pipes, interface): remove_all() reactor.addSystemEventTrigger('after', 'shutdown', remove_all) # gets default (outward-facing) network interface (e.g. deciding which of # eth0, eth1, wlan0 is being used by the system to connect to the internet) if interface == "auto": interface = netifaces.gateways()['default'][netifaces.AF_INET][1] else: if interface not in netifaces.interfaces(): raise ValueError("Given interface does not exist.", interface) add(protocol, port, interface) manager = libnetfilter_queue.Manager() manager.bind(UP_QUEUE, packet_handler(manager, pipes.up)) manager.bind(DOWN_QUEUE, packet_handler(manager, pipes.down)) reader = abstract.FileDescriptor() reader.doRead = manager.process reader.fileno = lambda: manager.fileno reactor.addReader(reader)
def start(self): try: os.makedirs(config_dir) except OSError: pass nodedirs = self.get_nodedirs() if nodedirs: for nodedir in nodedirs: gateway = Tahoe(nodedir) gateway.start() self.gateways.append(gateway) else: inv = InviteForm() inv.show() inv.raise_() self.tray = SystemTrayIcon(self) self.tray.show() reactor.addSystemEventTrigger('before', 'shutdown', self.stop) reactor.run()
def start(): log.startLogging(sys.stdout) factory = SpiderClientFactory("ws://{}:9000".format(ADMIN_HOST)) factory.protocol = TaskClientProtocol connectWS(factory) def killGroup(): for pid, kw in factory.spiders.iteritems(): try: p = psutil.Process(int(pid)) p.terminate() except Exception, e: print e reactor.addSystemEventTrigger('before', 'shutdown', killGroup)
def test_process_blob(self): client_factory_class = build_prism_blob_client_factory # start client from twisted.internet import reactor reactor.addSystemEventTrigger('before','shutdown', self._on_finish_blob) try: process_blob(BLOB_HASH, self.client_db_dir, client_factory_class, 'fake', host_infos=('localhost',5566,0), setup_d = self._setup_client_blobs) except SystemExit: pass # tell server process to stop self.server_queue.put('stop') # check client variables self.assertEqual(1, self.blob_exists) self.assertEqual(1, self.blob_has_been_forwarded) # file should be removed from client, because it was sent to server self.assertFalse(os.path.isfile(get_blob_path(BLOB_HASH, self.client_storage))) # check expected variables we should received from server server_results = self.client_queue.get() self.assertEqual(BLOB_CONTENT, server_results[0]['blob_content']) self.assertEqual(1, server_results[0]['blob_exists'])
def connect_with_retry(self): try: self.client.connect(self.broker_host, port=self.broker_port, keepalive=60) self.connect_loop.stop() except: log.failure(u'Error connecting to MQTT broker but retrying each {retry_interval} seconds', retry_interval=self.retry_interval) return """ This is part of the threaded client interface. Call this once to start a new thread to process network traffic. This provides an alternative to repeatedly calling loop() yourself. """ # TODO: Check whether reconnect works with this interface. self.client.loop_start() reactor.addSystemEventTrigger('before', 'shutdown', self.client.loop_stop, True) # The callback for when the client receives a CONNACK response from the server.
def run(self): """Loads plugins, and initiates polling schedules.""" reactor.callWhenRunning(self.install_sighandlers) if self.options.netbox: self.setup_single_job() elif self.options.multiprocess: self.setup_multiprocess(self.options.multiprocess, self.options.max_jobs) elif self.options.worker: self.setup_worker() else: self.setup_scheduling() reactor.suggestThreadPoolSize(self.options.threadpoolsize) reactor.addSystemEventTrigger("after", "shutdown", self.shutdown) reactor.run()
def run(self): def log_failure(failure): logger.exception(failure.value) if failure.frames: logger.critical(str("").join(format_tb(failure.getTracebackObject()))) def errback_main(failure): log_failure(failure) self.task.start(interval=0).addErrback(errback_main) def errback_flush_states(failure): log_failure(failure) self._flush_states_task.start(interval=300).addErrback(errback_flush_states) def debug(sig, frame): logger.critical("Signal received: printing stack trace") logger.critical(str("").join(format_stack(frame))) self.task.start(interval=0).addErrback(errback_main) self._logging_task.start(interval=30) self._flush_states_task.start(interval=300).addErrback(errback_flush_states) signal(SIGUSR1, debug) reactor.addSystemEventTrigger('before', 'shutdown', self.stop) reactor.run()
def test_singleStopCallback(self): """ L{task.react} doesn't try to stop the reactor if the L{defer.Deferred} the function it is passed is called back after the reactor has already been stopped. """ def main(reactor): reactor.callLater(1, reactor.stop) finished = defer.Deferred() reactor.addSystemEventTrigger( 'during', 'shutdown', finished.callback, None) return finished r = _FakeReactor() exitError = self.assertRaises( SystemExit, task.react, main, _reactor=r) self.assertEqual(r.seconds(), 1) self.assertEqual(0, exitError.code)
def test_duringPreceedsAfter(self): """ L{IReactorCore.addSystemEventTrigger} should call triggers added to the C{'during'} phase before it calls triggers added to the C{'after'} phase. """ eventType = 'test' events = [] def duringTrigger(): events.append('during') def afterTrigger(): events.append('after') self.addTrigger('during', eventType, duringTrigger) self.addTrigger('after', eventType, afterTrigger) self.assertEqual(events, []) reactor.fireSystemEvent(eventType) self.assertEqual(events, ['during', 'after'])
def test_removeNonExistentSystemEventTrigger(self): """ Passing an object to L{IReactorCore.removeSystemEventTrigger} which was not returned by a previous call to L{IReactorCore.addSystemEventTrigger} or which has already been passed to C{removeSystemEventTrigger} should result in L{TypeError}, L{KeyError}, or L{ValueError} being raised. """ b = self.addTrigger('during', 'test', lambda: None) self.removeTrigger(b) self.assertRaises( TypeError, reactor.removeSystemEventTrigger, None) self.assertRaises( ValueError, reactor.removeSystemEventTrigger, b) self.assertRaises( KeyError, reactor.removeSystemEventTrigger, (b[0], ('xxx',) + b[1][1:]))
def run(self, handler): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler)) reactor.listenTCP(self.port, factory, interface=self.host) if not reactor.running: reactor.run()
def startApplication(application, save): from twisted.internet import reactor service.IService(application).startService() if save: p = sob.IPersistable(application) reactor.addSystemEventTrigger('after', 'shutdown', p.save, 'shutdown') reactor.addSystemEventTrigger('before', 'shutdown', service.IService(application).stopService)
def onConnect(): # if keyAgent and options['agent']: # cc = protocol.ClientCreator(reactor, SSHAgentForwardingLocal, conn) # cc.connectUNIX(os.environ['SSH_AUTH_SOCK']) if hasattr(conn.transport, 'sendIgnore'): _KeepAlive(conn) if options.localForwards: for localPort, hostport in options.localForwards: s = reactor.listenTCP(localPort, forwarding.SSHListenForwardingFactory(conn, hostport, SSHListenClientForwardingChannel)) conn.localForwards.append(s) if options.remoteForwards: for remotePort, hostport in options.remoteForwards: log.msg('asking for remote forwarding for %s:%s' % (remotePort, hostport)) conn.requestRemoteForwarding(remotePort, hostport) reactor.addSystemEventTrigger('before', 'shutdown', beforeShutdown) if not options['noshell'] or options['agent']: conn.openChannel(SSHSession()) if options['fork']: if os.fork(): os._exit(0) os.setsid() for i in range(3): try: os.close(i) except OSError, e: import errno if e.errno != errno.EBADF: raise
def main(): mon = ProcessMonitor() mon.addProcess('foo', ['/bin/sh', '-c', 'sleep 2;echo hello']) mon.addProcess('qux', ['/bin/sh', '-c', 'sleep 2;printf pilim']) mon.addProcess('bar', ['/bin/sh', '-c', 'echo goodbye']) mon.addProcess('baz', ['/bin/sh', '-c', 'echo welcome;while :;do echo blah;sleep 5;done']) reactor.callLater(30, lambda mon=mon: os.kill(mon.protocols['baz'].transport.pid, SIGTERM)) reactor.callLater(60, mon.restartAll) mon.startService() reactor.addSystemEventTrigger('before', 'shutdown', mon.stopService) reactor.run()
def addTrigger(self, event, phase, func): t = reactor.addSystemEventTrigger(event, phase, func) self.triggers.append(t) return t
def start(self): """Start the connection pool. If you are using the reactor normally, this function does *not* need to be called. """ if not self.running: from twisted.internet import reactor self.threadpool.start() self.shutdownID = reactor.addSystemEventTrigger('during', 'shutdown', self.finalClose) self.running = True
def shutdown_process(self, shutdown_message, code=1): msg(shutdown_message) reactor.addSystemEventTrigger('after', 'shutdown', os._exit, code) reactor.stop()
def run(self, handler): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, handler)) reactor.listenTCP(self.port, factory, interface=self.host) reactor.run()
def twisted(app, address, **options): from twisted.web import server, wsgi from twisted.python.threadpool import ThreadPool from twisted.internet import reactor thread_pool = ThreadPool() thread_pool.start() reactor.addSystemEventTrigger('after', 'shutdown', thread_pool.stop) factory = server.Site(wsgi.WSGIResource(reactor, thread_pool, app)) reactor.listenTCP(address[1], factory, interface=address[0]) reactor.run()
def start_benchmark(self, seconds): self.iperf = subprocess.Popen('iperf -s -xS -yC'.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE) reactor.addSystemEventTrigger('before', 'shutdown', self.stop_benchmark) for client in self.clients: handle = self.clients[client][0] d = self.execute(handle, 'start_benchmark %d' % seconds) d.addCallback(lambda r, h=client : self.store_pid(h, r))
def main(): """Run application.""" # Hook up Qt application to Twisted. from twisted.internet import reactor # Make sure stopping twisted event also shuts down QT. reactor.addSystemEventTrigger('after', 'shutdown', app.quit) # Shutdown twisted when window is closed. app.connect(app, QtCore.SIGNAL("lastWindowClosed()"), reactor.stop) # Do not block test to finish. reactor.runReturn()
def __init__(self, cfg): self._reactor = reactor self._config_file = cfg # Set a cleanup function when reactor stops reactor.addSystemEventTrigger("before", "shutdown", self._cleanup)