class LocalUrwidService(service.Service): """Simple Service wrapper for a Twisted-Urwid bridge.""" def __init__(self, bridge_factory): self.bridge_factory = bridge_factory self.log_buffer = [] def startService(self): self.protocol = UrwidTerminalProtocol(self.bridge_factory) self.stdio = StandardIO(self.protocol) for args in self.log_buffer: self.protocol.bridge.add_log_line(*args) def stopService(self): self.stdio.loseConnection() del self.protocol del self.stdio def add_log_line(self, line, color): """I exist to allow the urwid app to take over logging.""" try: add_log_line = self.protocol.bridge.add_log_line except AttributeError: self.log_buffer.append((line, color)) else: add_log_line(line, color)
class ConsoleServer(ServerScript): connection_class = None def on_load(self): self.console = ConsoleInput(self.server) self.io = StandardIO(self.console) def on_unload(self): self.io.loseConnection()
class ConsoleServer(ServerScript): connection_class = None io = None def on_load(self): if not stdout.isatty(): return self.console = ConsoleInput(self.server) self.io = StandardIO(self.console) def on_unload(self): if self.io is None: return self.io.loseConnection()
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_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 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 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 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 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 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 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 __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 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 childConnectionLost(self, fd, reason): # the usual StandardIO class doesn't seem to handle half-closed stdio # well, specifically when our stdout is closed, then some data is # written to our stdin. The class responds to stdout's closure by # shutting down everything. I think this is related to # ProcessWriter.doRead returning CONNECTION_LOST instead of # CONNECTION_DONE (which ProcessWriter.connectionLost sends along to # StandardIO.childConnectionLost). There is code in # StandardIO.childConnectionLost to treat CONNECTION_DONE as a # half-close, but not CONNECTION_LOST. # # so this hack is to make it look more like a half-close #print >>sys.stderr, "my StandardIO.childConnectionLost", fd, reason.value from twisted.internet import error, main from twisted.python import failure if reason.check(error.ConnectionLost) and fd == "write": #print >>sys.stderr, " fixing" reason = failure.Failure(main.CONNECTION_DONE) return TwitchyStandardIO.childConnectionLost(self, fd, reason)
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 Commander(protobj): return StandardIO(_proxyCommander(protobj))
class ProgrammersChatClientProtocol(LineReceiver): name = '' def __init__(self): ProgrammersChatClientProtocol.state = 'SETNAME' ProgrammersChatClientProtocol.fileName = '' self.fileData = () self.fileSender = None self.state def connectionMade(self): print 'Connected to server.' forwarder = DataSenderProtocol(self) self.screen = StandardIO(forwarder) def lineReceived(self, line): print 'Line Received : ', line print 'State : ', ProgrammersChatClientProtocol.state if ProgrammersChatClientProtocol.state == 'CHAT': print 'Printing' self.screen.write('\n' + line + '\n' + self.name.join('<>')) print 'Printing finished' elif line.strip() == 'GETNAME': print('Enter Nick : ') elif line.strip() == 'NAMEBLOCK': print('Nick already in use. Try something else.') elif line.split()[0] == 'NAMESET': ProgrammersChatClientProtocol.state = 'CHAT' self.name = line.split()[1].strip() elif line.strip() == 'GET-FILE-SIZE': print 'Sending file size : ' self.fileSize = getsize(ProgrammersChatClientProtocol.fileName) self.sendLine(str(self.fileSize)) print 'File Size Sent' elif line.strip() == 'RECV-FILE': print 'Now sending...' self.sendLine(ProgrammersChatClientProtocol.fileName) #self.setRawMode() self.sendFile() print 'File Transfer Complete.' #def rawDataReceived(self, data): # pass def sendFile(self): if not self.fileSender: self.fileSender = open(ProgrammersChatClientProtocol.fileName, 'rb') while True: self.fileData = self.fileSender.read(256) if self.fileData: self.sendLine(self.fileData) else: #self.setLineMode() ProgrammersChatClientProtocol.state = 'CHAT' self.fileSender.close() self.fileSender = None self.fileData = () ProgrammersChatClientProtocol.fileName = '' return def handleCOMMAND(self, command): commandList = command.strip().split() if len(commandList) != 3: return 0 #try: ProgrammersChatClientProtocol.fileName = commandList[2] print 'Command Received : ', commandList print 'File Name : ', ProgrammersChatClientProtocol.fileName try: with open(ProgrammersChatClientProtocol.fileName): print 'Setting state.' ProgrammersChatClientProtocol.fileSize = getsize(ProgrammersChatClientProtocol.fileName) ProgrammersChatClientProtocol.state = 'SEND-FILE' print 'Setting state...' self.sendLine(ProgrammersChatClientProtocol.state) print 'Command state : ', ProgrammersChatClientProtocol.state print 'Line sent...' #self.sendLine(self.fileName) #self.fileName = command.strip().split() #self.setRawMode() print 'Getting out' return 1 except IOError: print 'IOError' return -1
def connectionMade(self): print 'Connected to server.' forwarder = DataSenderProtocol(self) self.screen = StandardIO(forwarder)
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 startService(self): self.protocol = UrwidTerminalProtocol(self.bridge_factory) self.stdio = StandardIO(self.protocol) for args in self.log_buffer: self.protocol.bridge.add_log_line(*args)
def __init__(self, protocol, factory): protocol.factory = factory StandardIO.__init__(self, protocol)
def on_load(self): if not stdout.isatty(): return self.console = ConsoleInput(self.server) self.io = StandardIO(self.console)
def on_load(self): self.console = ConsoleInput(self.server) self.io = StandardIO(self.console)
def main(reactor, magicString): p = LastWriteChild(reactor, magicString.encode("ascii")) StandardIO(p) reactor.run()