我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.python.log.startLogging()。
def main(): log.startLogging(sys.stdout) captchaKey = crypto.getKey(FARFETCHD_CAPTCHA_HMAC_KEYFILE) hmacKey = crypto.getHMAC(captchaKey, "Captcha-Key") # Load or create our encryption keys: secretKey, publicKey = crypto.getRSAKey(FARFETCHD_CAPTCHA_RSA_KEYFILE) index = CaptchaResource() fetch = CaptchaFetchResource(hmacKey, publicKey, secretKey) check = CaptchaCheckResource(hmacKey, publicKey, secretKey) root = index root.putChild("fetch", fetch) root.putChild("check", check) site = HttpJsonApiServer(root) port = FARFETCHD_HTTP_PORT or 80 host = FARFETCHD_HTTP_HOST or '127.0.0.1' reactor.listenTCP(port, site, interface=host) reactor.run()
def startLogging(logfilename, sysLog, prefix, nodaemon): if logfilename == '-': if not nodaemon: print 'daemons cannot log to stdout' os._exit(1) logFile = sys.stdout elif sysLog: syslog.startLogging(prefix) elif nodaemon and not logfilename: logFile = sys.stdout else: logFile = app.getLogFile(logfilename or 'twistd.log') try: import signal except ImportError: pass else: def rotateLog(signal, frame): from twisted.internet import reactor reactor.callFromThread(logFile.rotate) signal.signal(signal.SIGUSR1, rotateLog) if not sysLog: log.startLogging(logFile) sys.stdout.flush()
def run(argv=sys.argv): log.startLogging(file('tkunzip.log', 'w')) opt=TkunzipOptions() try: opt.parseOptions(argv[1:]) except usage.UsageError, e: print str(opt) print str(e) sys.exit(1) if opt['use-console']: # this should come before shell-exec to prevent infinite loop return doItConsolicious(opt) if opt['shell-exec'] or not 'Tkinter' in sys.modules: from distutils import sysconfig from twisted.scripts import tkunzip myfile=tkunzip.__file__ exe=os.path.join(sysconfig.get_config_var('prefix'), 'python.exe') return os.system('%s %s --use-console %s' % (exe, myfile, ' '.join(argv[1:]))) return doItTkinterly(opt)
def run(): # import hotshot # prof = hotshot.Profile('cftp.prof') # prof.start() args = sys.argv[1:] if '-l' in args: # cvs is an idiot i = args.index('-l') args = args[i:i+2]+args del args[i+2:i+4] options = ClientOptions() try: options.parseOptions(args) except usage.UsageError, u: print 'ERROR: %s' % u sys.exit(1) if options['log']: realout = sys.stdout log.startLogging(sys.stderr) sys.stdout = realout else: log.discardLogs() doConnect(options) reactor.run() # prof.stop() # prof.close()
def __init__(self,server,port,secret,requests,concurrency,username,password, verb=False,timeout=600,rate=1000): logname = "/tmp/trbctl-worker-{}.log".format(os.environ.get("LOGID",0)) log.startLogging(open(logname,'w')) self.timeout = timeout self.pusher = ZmqPushConnection(ZmqFactory(), ZmqEndpoint('connect', 'ipc:///tmp/toughbt-message')) self.pusher.push("write worker %s log into %s" % (os.getpid(),logname)) log.msg("init BenchmarkWorker pusher : %s " % repr(self.pusher)) # define client cycle list raddict = dictionary.Dictionary(os.path.join(os.path.dirname(__file__),"dictionary")) new_cli = lambda : RadAuthClient(str(secret), raddict, server,port=port,debug=verb,stat_push=self.pusher) clis = itertools.cycle([new_cli() for c in range(concurrency)]) # send radius message send = lambda:next(clis).sendAuth(**{'User-Name' : username,'User-Password':password}) send_rate = 1.0/rate send_delay = send_rate for i in xrange(requests): reactor.callLater(send_delay,send) send_delay += send_rate reactor.callLater(self.timeout,self.on_timeout)
def create(URI, resource_type, payload, origin=None, requestID=None): uri = urlparse(URI) if uri.scheme == "http": response = ciotdm.create(URI, resource_type, payload, origin, requestID) print str(response[0]) + '\n' + response[1] elif uri.scheme == "coap": log.startLogging(sys.stdout) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) Agent(protocol, "post", URI, payload=payload, ty=resource_type, origin=origin, requestID=requestID) reactor.listenUDP(0, protocol) reactor.run() else: print "Invalid protocol." sys.exit(2)
def retrieve(URI, origin=None, requestID=None): uri = urlparse(URI) if uri.scheme == "http": response = ciotdm.retrieve(URI, origin, requestID) print str(response[0]) + '\n' + response[1] elif uri.scheme == "coap": log.startLogging(sys.stdout) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) Agent(protocol, "get", URI, origin=origin, requestID=requestID) reactor.listenUDP(0, protocol) reactor.run() else: print "Invalid protocol." sys.exit(2)
def update(URI, payload, origin=None, requestID=None): uri = urlparse(URI) if uri.scheme == "http": response = ciotdm.update(URI, payload, origin, requestID) print str(response[0]) + '\n' + response[1] elif uri.scheme == "coap": log.startLogging(sys.stdout) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) Agent(protocol, "put", URI, payload=payload, origin=origin, requestID=requestID) reactor.listenUDP(0, protocol) reactor.run() else: print "Invalid protocol." sys.exit(2)
def delete(URI, origin=None, requestID=None): uri = urlparse(URI) if uri.scheme == "http": response = ciotdm.delete(URI, origin, requestID) print str(response[0]) + '\n' + response[1] elif uri.scheme == "coap": log.startLogging(sys.stdout) endpoint = resource.Endpoint(None) protocol = coap.Coap(endpoint) Agent(protocol, "delete", URI, origin=origin, requestID=requestID) reactor.listenUDP(0, protocol) reactor.run() else: print "Invalid protocol." sys.exit(2)
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 main(): log.startLogging(sys.stdout) launch_tor = True if launch_tor: c = TorConfig() #FIXME: check these values, parametize! c.CircuitBuildTimeout = 20 c.LearnCircuitBuildTimeout = 0 c.CircuitIdleTimeout = 20 c.FetchDirInfoEarly = 1 c.FetchDirInfoExtraEarly = 1 c.FetchUselessDescriptors = 1 tor = start_tor(c) else: tor = build_local_tor_connection(reactor) tor.addCallback(setconf_fetch_all_descs) # check that each run is producing the same input set! tor.addCallback(BwScan, reactor, './logs', partitions=1, this_partition=0) tor.addCallback(lambda scanner: scanner.run_scan()) tor.addCallback(lambda _: reactor.stop()) reactor.run()
def run(): log.startLogging(sys.stdout) if len(sys.argv) > 1 and sys.argv[1] == 'debug': debug = True else: debug = False # startup greeting #tts_say('Herzlich Willkommen') WEBSOCKET_URI = 'ws://localhost:9000' #WEBSOCKET_URI = 'ws://master.example.com:9000' boot_node(WEBSOCKET_URI, debug) reactor.run()
def run(): # import hotshot # prof = hotshot.Profile('cftp.prof') # prof.start() args = sys.argv[1:] if '-l' in args: # cvs is an idiot i = args.index('-l') args = args[i:i+2]+args del args[i+2:i+4] options = ClientOptions() try: options.parseOptions(args) except usage.UsageError as u: print('ERROR: %s' % u) sys.exit(1) if options['log']: realout = sys.stdout log.startLogging(sys.stderr) sys.stdout = realout else: log.discardLogs() doConnect(options) reactor.run() # prof.stop() # prof.close()
def test_printToStderrSetsIsError(self): """ startLogging()'s overridden sys.stderr should consider everything written to it an error. """ self._startLoggingCleanup() fakeFile = StringIO() log.startLogging(fakeFile) def observe(event): observed.append(event) observed = [] log.addObserver(observe) print("Hello, world.", file=sys.stderr) self.assertEqual(observed[0]["isError"], 1)
def test_startLoggingTwice(self): """ There are some obscure error conditions that can occur when logging is started twice. See http://twistedmatrix.com/trac/ticket/3289 for more information. """ self._startLoggingCleanup() # The bug is particular to the way that the t.p.log 'global' function # handle stdout. If we use our own stream, the error doesn't occur. If # we use our own LogPublisher, the error doesn't occur. sys.stdout = StringIO() def showError(eventDict): if eventDict['isError']: sys.__stdout__.write(eventDict['failure'].getTraceback()) log.addObserver(showError) self.addCleanup(log.removeObserver, showError) observer = log.startLogging(sys.stdout) self.addCleanup(observer.stop) # At this point, we expect that sys.stdout is a StdioOnnaStick object. self.assertIsInstance(sys.stdout, LoggingFile) fakeStdout = sys.stdout observer = log.startLogging(sys.stdout) self.assertIs(sys.stdout, fakeStdout)
def startTwisted(self): from twisted.python import log log.startLogging(open("wssserver.log", "w")) self.print_debug("startTwisted() started") ws = "ws" ResourceProtocol.server = self sslcontext = None if self.ssl: self.print_debug("using wss... and ssl") sslcontext = ssl.DefaultOpenSSLContextFactory(self.sslkey, self.sslcert) ws = "wss" factory = WebSocketServerFactory(u"{}://127.0.0.1:{}".format(ws, self.port)) factory.protocol = ResourceProtocol listenWS(factory, sslcontext) reactor.run()
def preApplication(self): """ Do pre-application-creation setup. """ checkPID(self.config['pidfile']) self.config['nodaemon'] = (self.config['nodaemon'] or self.config['debug']) self.oldstdout = sys.stdout self.oldstderr = sys.stderr startLogging(self.config['logfile'], self.config['syslog'], self.config['prefix'], self.config['nodaemon']) app.initialLog()
def startLogging(logfilename): if logfilename == '-' or not logfilename: logFile = sys.stdout else: logFile = app.getLogFile(logfilename) log.startLogging(logFile) sys.stdout.flush()
def preApplication(self): """ Do pre-application-creation setup. """ self.oldstdout = sys.stdout self.oldstderr = sys.stderr startLogging(self.config['logfile']) app.initialLog() os.chdir(self.config['rundir'])
def failed(err): log.startLogging(sys.stderr) log.err(err)
def dataReceived(self, bytes): self.buf += bytes if self._paused: log.startLogging(sys.stderr) log.msg("dataReceived while transport paused!") self.transport.loseConnection() else: self.transport.write(bytes) if self.buf.endswith('\n0\n'): self.transport.loseConnection() else: self.pause()
def _captureLocalLog(self): return log.startLogging(_Notafile(self, "log"), setStdout=False)
def set_up_client(): # set up client with: # # set Twisted debug level # connect to the db global dbconn, dbd, dbpool DEBUG_MODE = True setDebugging(DEBUG_MODE) log.startLogging(sys.stdout) # db connection and deferred dbconn = txpostgres.Connection() dbd = dbconn.connect("dbname=news user=user password=test1 host=127.0.0.1 application_name='news-collect'") dbpool = adbapi.ConnectionPool('psycopg2', dbname='news', user='user', password='test1')
def run(self) -> None: log.startLogging(open(datetime.now().strftime('logs/websocket_%d_%m_%Y.log'), 'a')) factory = MyClientFactory(self.URL) factory.protocol = self.protocol connectWS(factory) default_handler = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, signal.SIG_IGN) reactor.run() signal.signal(signal.SIGINT, default_handler) if reactor.running: reactor.stop()
def ebConnection(reason): """ Fallback error-handler. If anything goes wrong, log it and quit. """ log.startLogging(sys.stdout) log.err(reason) return reason
def main(): # initialize logging log.startLogging(sys.stdout) # create factory protocol and application f = BotFactory("logs.log") # connect factory to this host and port reactor.connectTCP(config.server, 6667, f) # run bot reactor.run()
def start(): config = Options() try: config.parseOptions() except usage.UsageError as errortext: print('{}: {}'.format(sys.argv[0], errortext)) print('{}: Try --help for usage details'.format(sys.argv[0])) sys.exit(1) if config.subCommand == 'lirc_config': log.msg('Writing default lircrc to {}'.format(config.subOptions['path'])) lirc.write_default_config(config.subOptions['path'], config.subOptions['program_name'], config.subOptions['remote']) sys.exit(0) elif config.subCommand == 'run': from twisted.internet import reactor observer = log.startLogging(sys.stdout) observer.timeFormat = '' log.msg('Starting...') # noinspection PyTypeChecker iscp_service = makeService(config.subOptions) iscp_service.startService() reactor.run() else: raise usage.UsageError('Unknown subcommand {}'.format(config.subCommand))
def pytest_runtest_setup(item): if item.config.getoption("--twisted-logs"): import sys from twisted.python import log log.startLogging(sys.stdout)
def __init__(self, shell): super(JunoMagics, self).__init__(shell) self._router_url = os.environ.get("JUPYTER_WAMP_ROUTER", "wss://juno.timbr.io/wamp/route") self._realm = os.environ.get("JUPYTER_WAMP_REALM", "jupyter") self._wamp = None self._wamp_runner = None self._kernel_prefix = None # NOTE: this strategy only seems to work in kernels launched by the notebook server self._connection_file = get_ipython().config["IPKernelApp"]["connection_file"] self._token = os.environ.get("JUNO_AUTH_TOKEN") self._sp = None self._connected = None self._hb_interval = 5 self._heartbeat = LoopingCall(self._ping) self._debug = True self._wamp_event_dispatcher = WampEventDispatcher(self) self._kernel_event_dispatcher = KernelEventDispatcher() self._interrupt_timeout = 5 # Wait time before notifying interrupt failure self._execute_timeout = 120 # Wait time before notifying long running execution self._queue = Queue.Queue() self._last_msg_id = None if self._debug: try: log.startLogging(open('/home/gremlin/wamp.log', 'w'), setStdout=False) except IOError: pass try: # set local kernel key with open(self._connection_file) as f: config = json.load(f) self._kernel_key = config["key"] except TypeError: self._kernel_key = None self._parser = self.generate_parser()
def setup_wallets(): log.startLogging(sys.stdout) load_coinswap_config() #need to give up waiting for confirms artificially quickly cs_single().one_confirm_timeout = 20 cs_single().num_entities_running = 0
def start_logging(out=_stdout, level='info'): """ Start logging to the file-like object in ``out``. By default, this is stdout. """ global _loggers, _observer, _log_level, _started_logging if level not in log_levels: raise RuntimeError( "Invalid log level '{0}'; valid are: {1}".format( level, ', '.join(log_levels) ) ) if _started_logging: return _started_logging = True _log_level = level set_global_log_level(_log_level) if out: _observer = _LogObserver(out) if _NEW_LOGGER: _observers = [] if _observer: _observers.append(_observer) globalLogBeginner.beginLoggingTo(_observers) else: assert out, "out needs to be given a value if using Twisteds before 15.2" from twisted.python import log log.startLogging(out)
def main(tor_control, tor_data): log.startLogging( sys.stdout ) def start_tor(): config = txtorcon.TorConfig() config.DataDirectory = tor_data def get_random_tor_ports(): d2 = txtorcon.util.available_tcp_port(reactor) d2.addCallback(lambda port: config.__setattr__('SocksPort', port)) d2.addCallback(lambda _: txtorcon.util.available_tcp_port(reactor)) d2.addCallback(lambda port: config.__setattr__('ControlPort', port)) return d2 def launch_and_get_protocol(ignore): d2 = txtorcon.launch_tor(config, reactor, stdout=sys.stdout) d2.addCallback(lambda tpp: txtorcon.TorState(tpp.tor_protocol).post_bootstrap) d2.addCallback(lambda state: state.protocol) return d2 d = get_random_tor_ports().addCallback(launch_and_get_protocol) def change_torrc(result): config.UseEntryGuards=0 d2 = config.save() d2.addCallback(lambda ign: result) return d2 d.addCallback(change_torrc) d.addCallback(lambda protocol: TorState.from_protocol(protocol)) return d if tor_control is None: print "launching tor..." d = start_tor() else: print "using tor control port..." endpoint = clientFromString(reactor, tor_control.encode('utf-8')) d = txtorcon.build_tor_connection(endpoint, build_state=False) d.addCallback( ProbeAll2HopCircuits, reactor, './logs', stopped=reactor.stop ) reactor.run()
def main(): log.startLogging(sys.stdout) tor = start_tor(TorConfig()) tor.addCallback(add_attacher) tor.addCallback(run_scan) tor.addErrback(log.err) tor.addBoth(shutdown) reactor.run()
def startStt(self, audioFd): # logging log.startLogging(sys.stdout) hostname = "stream.watsonplatform.net" headers = {} # authentication header if self.configData["tokenauth"]: headers['X-Watson-Authorization-Token'] = Utils.getAuthenticationToken("https://" + hostname, 'speech-to-text', self.configData["user"], self.configData["password"]) else: string = self.configData["user"] + ":" + self.configData["password"] headers["Authorization"] = "Basic " + base64.b64encode(string) # create a WS server factory with our protocol url = "wss://" + hostname + "/speech-to-text/api/v1/recognize?model=" + self.configData["model"] summary = {} factory = WSInterfaceFactory(audioFd, summary, self.CONTENT_TYPE, self.configData["model"], url, headers, debug=False) factory.setListeners(self.listeners) factory.protocol = WSInterfaceProtocol if factory.isSecure: contextFactory = ssl.ClientContextFactory() else: contextFactory = None connectWS(factory, contextFactory) reactor.run()
def main(): # log.startLogging(sys.stdout) sim_time() factory = WebSocketClientFactory(u'ws://127.0.0.1:9000') factory.protocol = Client reactor.connectTCP('127.0.0.1', 9000, factory) reactor.run()
def main(): # log.startLogging(sys.stdout) sim_time() factory = WebSocketServerFactory(u'ws://127.0.0.1:9000') factory.protocol = Server reactor.listenTCP(9000, factory) reactor.run()
def run_wamp_client(): log.startLogging(sys.stdout) runner = ApplicationRunner("ws://localhost:9000/ws", "kotori-realm") #runner = ApplicationRunner("ws://master.example.com:9000/ws", "kotori-realm") runner.run(KotoriClient, start_reactor=False) reactor.run()
def run(): if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False websocket_uri = 'ws://localhost:9000' http_port = 35000 boot_master(websocket_uri, http_port, debug) reactor.run()
def run_udp_client(): log.startLogging(sys.stdout) #data = 'UDP hello' #data = '5;3;' try: data = sys.argv[1] except IndexError: data = '' sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.sendto(data, ('127.0.0.1', 7777))
def run_udp_fuzzer(): log.startLogging(sys.stdout) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) while True: data = generate_packet() print 'packet:', data sock.sendto(data, ('127.0.0.1', 7777)) time.sleep(0.25)
def main(argv): options = parse_options(argv[1:]) if options.log: log.startLogging(sys.stdout) factory = FtpServerFactory(options.root_path, options.port) factory.makeListener() twisted.internet.reactor.run()