def test_addReader(self): """ Adding a filesystem file reader to a reactor will make sure it is polled. """ reactor = self.buildReactor() class DataProtocol(Protocol): data = b"" def dataReceived(self, data): self.data += data # It'd be better to stop reactor on connectionLost, but that # fails on FreeBSD, probably due to # http://bugs.python.org/issue9591: if self.data == b"hello!": reactor.stop() path = self.mktemp() with open(path, "wb") as f: f.write(b"hello!") with open(path, "rb") as f: # Read bytes from a file, deliver them to a protocol instance: protocol = DataProtocol() StandardIO(protocol, stdin=f.fileno(), stdout=self.extraFile.fileno(), reactor=reactor) self.runReactor(reactor) self.assertEqual(protocol.data, b"hello!")
def test_removeAll(self): """ Calling C{removeAll} on a reactor includes descriptors that are filesystem files. """ reactor = self.buildReactor() self.addCleanup(self.unbuildReactor, reactor) path = self.mktemp() open(path, "wb").close() # Cleanup might fail if file is GCed too soon: self.f = f = open(path, "rb") # Have the reader added: stdio = StandardIO( Protocol(), stdin=f.fileno(), stdout=self.extraFile.fileno(), reactor=reactor, ) # And then removed: removed = reactor.removeAll() self.assertIn(stdio._reader, removed) self.assertNotIn(stdio._reader, reactor.getReaders())
def test_addWriter(self): """ Adding a filesystem file writer to a reactor will make sure it is polled. """ reactor = self.buildReactor() class DisconnectProtocol(Protocol): def connectionLost(self, reason): reactor.stop() path = self.mktemp() with open(path, "wb") as f: # Write bytes to a transport, hopefully have them written to a # file: protocol = DisconnectProtocol() StandardIO(protocol, stdout=f.fileno(), stdin=self.extraFile.fileno(), reactor=reactor) protocol.transport.write(b"hello") protocol.transport.write(b", world") protocol.transport.loseConnection() self.runReactor(reactor) with open(path, "rb") as f: self.assertEqual(f.read(), b"hello, world")
def runTextServer(reactor, *argv): """ Run a L{ConsoleTextServer}. """ textServer = makeTextServer(reactor, *argv) StandardIO(ServerProtocol(lambda: textServer)) return textServer.done
def main(): log_info("main %s", sys.argv) global stdio f = ProxyClientFactory() reactor.connectTCP("127.0.0.1", 9999, f) stdio = Stdio() StandardIO(stdio) reactor.run()
def main(**kwargs): app = QtApplication() qt5reactor.install() view = ViewerWindow(filename=kwargs.get('file', '-'), frameless=kwargs.get('frameless', False)) view.protocol = ViewerProtocol(view) view.show() app.deferred_call(lambda: StandardIO(view.protocol)) app.start()
def trySetup(addr, port): chat = Protocol() site = twisted.web.server.Site(twisted.web.static.File(public)) reactor.listenUDP(port, chat) reactor.listenTCP(port + 1, site) StandardIO(ConsoleHandler(chat)) print("Tell your friends /add [{}]:{}".format(addr, port)) with commands.init(stdin): reactor.run()
def start_tunnel(self, options): """ Main method to startup a tunnel helper and add a signal handler. """ socks5_port = options["socks5"] introduce_port = options["introduce"] dispersy_port = options["dispersy"] crawl_keypair_filename = options["crawl"] settings = TunnelSettings() # For disabling anonymous downloading, limiting download to hidden services only. settings.min_circuits = 0 settings.max_circuits = 0 if socks5_port is not None: settings.socks_listen_ports = range(socks5_port, socks5_port + 5) else: settings.socks_listen_ports = [random.randint(1000, 65535) for _ in range(5)] settings.become_exitnode = bool(options["exit"]) if settings.become_exitnode: logger.info("Exit-node enabled") else: logger.info("Exit-node disabled") settings.enable_trustchain = bool(options["trustchain"]) if settings.enable_trustchain: logger.info("Trustchain enabled") else: logger.info("Trustchain disabled") tunnel = Tunnel(settings, crawl_keypair_filename, dispersy_port) StandardIO(LineHandler(tunnel)) def stop_tunnel_api(): if self.tunnel_site: return maybeDeferred(self.tunnel_site.stopListening) return succeed(None) def signal_handler(sig, _): msg("Received shut down signal %s" % sig) if not self._stopping: self._stopping = True msg("Setting the tunnel should_run variable to False") tunnel.should_run = False tunnel.stop().addCallback(lambda _: stop_tunnel_api().addCallback(lambda _: reactor.stop())) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) tunnel.start(introduce_port) if options["tunnelapi"] > 0: self.tunnel_site = self.site = reactor.listenTCP(options["tunnelapi"], server.Site(resource=TunnelRootEndpoint(tunnel)))
def rapuiSetupForkChildVortexClient(logger): if not 'childprocess' in sys.argv: return protocol = ForkChildVortexClientProtocol(logger=logger) ModData.standardIo = StandardIO(protocol, stdout=VORTEX_PARENT_IN_FD) # Vortex._instance = ForkChildVortex(protocol) ModData.killCheckLoopingCall = task.LoopingCall(_parentPidCheck) ModData.killCheckLoopingCall.start(0.2)
def __init__(self, event_bus, hosts, verbose_logging, pause_after): HeadlessFrontend.__init__(self, event_bus, hosts, verbose_logging) self.console_input = StdioListener() StandardIO(self.console_input) event_bus.register({ "deploy.sleep": self.on_sleep, "deploy.enqueue": self.on_enqueue, }) self.pause_after = pause_after self.enqueued_hosts = 0
def startCGI(site): """Call this as the last thing in your CGI python script in order to hook up your site object with the incoming request. E.g.: >>> from twisted.web2 import channel, server >>> if __name__ == '__main__': ... channel.startCGI(server.Site(myToplevelResource)) """ from twisted.internet.stdio import StandardIO StandardIO(CGIChannelRequest(site, os.environ)) reactor.run()
def doWork(self): """ Service startup. """ # Set up the terminal for interactive action self.terminalFD = sys.__stdin__.fileno() self._oldTerminalSettings = termios.tcgetattr(self.terminalFD) tty.setraw(self.terminalFD) self.protocol = ServerProtocol(lambda: ShellProtocol(self)) StandardIO(self.protocol) return succeed(None)
def start_console(): ag = AMPGateway("localhost", 25600) if fancy_console: global oldSettings fd = sys.__stdin__.fileno() oldSettings = termios.tcgetattr(fd) tty.setraw(fd) p = ServerProtocol(BravoManhole, ag) else: p = BravoConsole(ag) StandardIO(p) return p
def test_getReaders(self): """ C{reactor.getReaders} includes descriptors that are filesystem files. """ reactor = self.buildReactor() self.addCleanup(self.unbuildReactor, reactor) path = self.mktemp() open(path, "wb").close() # Cleanup might fail if file is GCed too soon: with open(path, "rb") as f: # Have the reader added: stdio = StandardIO(Protocol(), stdin=f.fileno(), stdout=self.extraFile.fileno(), reactor=reactor) self.assertIn(stdio._reader, reactor.getReaders())
def test_getWriters(self): """ C{reactor.getWriters} includes descriptors that are filesystem files. """ reactor = self.buildReactor() self.addCleanup(self.unbuildReactor, reactor) # Cleanup might fail if file is GCed too soon: self.f = f = open(self.mktemp(), "wb") # Have the reader added: stdio = StandardIO(Protocol(), stdout=f.fileno(), stdin=self.extraFile.fileno(), reactor=reactor) self.assertNotIn(stdio._writer, reactor.getWriters()) stdio._writer.startWriting() self.assertIn(stdio._writer, reactor.getWriters())
def main(**kwargs): app = QtApplication() qreactor.install() filename = kwargs.get('file', '-') frameless = kwargs.get('frameless', False) watch = kwargs.get('watch', False) if not frameless and not os.path.exists(filename): raise ValueError("File %s does not exist!" % filename) view = ViewerWindow(filename='-', frameless=frameless) view.protocol = ViewerProtocol(view, watch) view.show() app.deferred_call(lambda: StandardIO(view.protocol)) app.deferred_call(view.protocol.handle_filename, filename) app.start()
def __init__(self, event_bus, hosts, verbose_logging, config): HeadlessFrontend.__init__(self, event_bus, hosts, verbose_logging) self.console_input = StdioListener() StandardIO(self.console_input) event_bus.register({ "deploy.precheck": self.on_precheck, "deploy.sleep": self.on_sleep, }) self.config = config pools = set(host.pool for host in hosts) if len(pools) > 1: self.deploy_strategy = FirstHostDeployStrategy(self.console_input) else: self.deploy_strategy = CanaryDeployStrategy(self.console_input)
def test_removeReader(self): """ Removing a filesystem file reader from a reactor will make sure it is no longer polled. """ reactor = self.buildReactor() self.addCleanup(self.unbuildReactor, reactor) path = self.mktemp() open(path, "wb").close() with open(path, "rb") as f: # Have the reader added: stdio = StandardIO(Protocol(), stdin=f.fileno(), stdout=self.extraFile.fileno(), reactor=reactor) self.assertIn(stdio._reader, reactor.getReaders()) stdio._reader.stopReading() self.assertNotIn(stdio._reader, reactor.getReaders())
def start_tunnel(self, options): """ Main method to startup a tunnel helper and add a signal handler. """ tunnel = Tunnel(options, options["ipv8_port"], options["ipv8_address"]) StandardIO(LineHandler(tunnel)) def signal_handler(sig, _): msg("Received shut down signal %s" % sig) if not self._stopping: self._stopping = True msg("Setting the tunnel should_run variable to False") tunnel.should_run = False tunnel.stop().addCallback(lambda _: reactor.stop()) signal.signal(signal.SIGINT, signal_handler) signal.signal(signal.SIGTERM, signal_handler) tunnel.start()
def test_removeWriter(self): """ Removing a filesystem file writer from a reactor will make sure it is no longer polled. """ reactor = self.buildReactor() self.addCleanup(self.unbuildReactor, reactor) # Cleanup might fail if file is GCed too soon: self.f = f = open(self.mktemp(), "wb") # Have the reader added: protocol = Protocol() stdio = StandardIO(protocol, stdout=f.fileno(), stdin=self.extraFile.fileno(), reactor=reactor) protocol.transport.write(b"hello") self.assertIn(stdio._writer, reactor.getWriters()) stdio._writer.stopWriting() self.assertNotIn(stdio._writer, reactor.getWriters())
def runmain(): import traceback try: __import__("twext") from twisted.python.log import startLogging from sys import exit, stderr startLogging(stderr) from twisted.internet import reactor from twisted.internet.stdio import StandardIO from contrib.performance.loadtest.ampsim import Worker # @UnresolvedImport from contrib.performance.loadtest.sim import LagTrackingReactor StandardIO(Worker(LagTrackingReactor(reactor))) reactor.run() except: traceback.print_exc() exit(1) else: exit(0)
def main(cfg, dnsDomain): try: baseDN = cfg.getBaseDN() except config.MissingBaseDNError as e: print("{}: {}.".format(sys.argv[0], e), file=sys.stderr) sys.exit(1) def ldapEntryFactory(pdnsProto): c = ldapconnector.LDAPClientCreator(reactor, MyLDAPClient, pdnsProto=pdnsProto) d = c.connectAnonymously(dn=baseDN, overrides=cfg.getServiceLocationOverrides()) def _cb(client, baseDN): e = LDAPEntry(client=client, dn=baseDN) return e d.addCallback(_cb, baseDN) return d pdnsPipeProtocol = PdnsPipeProtocol(ldapEntryFactory, dnsDomain) reactor.addReader(StandardIO(pdnsPipeProtocol)) reactor.run() sys.exit(exitStatus)
def main(reactor, magicString): p = LastWriteChild(reactor, magicString.encode("ascii")) StandardIO(p) reactor.run()
def main(reactor, magicString): p = LastWriteChild(reactor, magicString) StandardIO(p) reactor.run()
def create_console(protocol): console = ConsoleInput(protocol) StandardIO(console)
protocolClass = namedAny(there) proto = protocolClass() origLost = proto.connectionLost def goodbye(reason): """ Stop the process if stdin is closed. """ try: reactor.stop() except ReactorNotRunning: pass return origLost(reason) proto.connectionLost = goodbye StandardIO(proto) from twisted.internet import reactor reactor.run() os._exit(0) from zope.interface import implements from twisted.internet.interfaces import ITransport, IPushProducer, IConsumer from twisted.application.service import Service from twisted.python.reflect import qual from twisted.internet.protocol import ProcessProtocol from twisted.internet.defer import Deferred, succeed class BridgeTransport(object):
def run(protocol): StandardIO(protocol) reactor.run(installSignalHandlers=False)
def connectionMade(self): StandardIO(Sender(self))
#!C:\Python27\Python from mudpyl.modules import BaseModule from mudpyl.realms import RootRealm from twisted.internet.stdio import StandardIO class MainModule(RootRealm): pass StandardIO(MainModule()) from twisted.internet import reactor reactor.run()
def Commander(protobj): return StandardIO(_proxyCommander(protobj))