我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用twisted.python.log.deferr()。
def _doReadOrWrite(self, selectable, fd, event, POLLIN, POLLOUT, log, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()) }): why = None inRead = False if event & POLL_DISCONNECTED and not (event & POLLIN): why = main.CONNECTION_LOST else: try: if event & POLLIN: why = selectable.doRead() inRead = True if not why and event & POLLOUT: why = selectable.doWrite() inRead = False if not selectable.fileno() == fd: why = error.ConnectionFdescWentAway('Filedescriptor went away') inRead = False except: log.deferr() why = sys.exc_info()[1] if why: self._disconnectSelectable(selectable, why, inRead)
def _worker(self, o): ct = threading.currentThread() while 1: if o is WorkerStop: break elif o is not None: self.working.append(ct) ctx, function, args, kwargs = o try: context.call(ctx, function, *args, **kwargs) except: context.call(ctx, log.deferr) self.working.remove(ct) del o, ctx, function, args, kwargs self.waiters.append(ct) o = self.q.get() self.waiters.remove(ct) self.threads.remove(ct)
def getApplication(config, passphrase): s = [(config[t], t) for t in ['python', 'xml', 'source', 'file'] if config[t]][0] filename, style = s[0], {'file':'pickle'}.get(s[1],s[1]) try: log.msg("Loading %s..." % filename) application = service.loadApplication(filename, style, passphrase) log.msg("Loaded.") except Exception, e: s = "Failed to load application: %s" % e if isinstance(e, KeyError) and e.args[0] == "application": s += """ Could not find 'application' in the file. To use 'twistd -y', your .tac file must create a suitable object (e.g., by calling service.Application()) and store it in a variable named 'application'. twistd loads your .tac file and scans the global variables for one of this name. Please read the 'Using Application' HOWTO for details. """ traceback.print_exc(file=log.logfile) log.msg(s) log.deferr() sys.exit('\n' + s + '\n') return application
def doConnect(options): # log.deferr = handleError # HACK if '@' in options['host']: options['user'], options['host'] = options['host'].split('@',1) host = options['host'] if not options['user']: options['user'] = getpass.getuser() if not options['port']: options['port'] = 22 else: options['port'] = int(options['port']) host = options['host'] port = options['port'] conn = SSHConnection() conn.options = options vhk = default.verifyHostKey uao = default.SSHUserAuthClient(options['user'], options, conn) connect.connect(host, port, options, vhk, uao).addErrback(_ebExit)
def doConnect(): # log.deferr = handleError # HACK if '@' in options['host']: options['user'], options['host'] = options['host'].split('@',1) if not options.identitys: options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa'] host = options['host'] if not options['user']: options['user'] = getpass.getuser() if not options['port']: options['port'] = 22 else: options['port'] = int(options['port']) host = options['host'] port = options['port'] vhk = default.verifyHostKey uao = default.SSHUserAuthClient(options['user'], options, SSHConnection()) connect.connect(host, port, options, vhk, uao).addErrback(_ebExit)
def mainLoop(self): while self.running: try: while self.running: # Advance simulation time in delayed event # processors. self.runUntilCurrent() t2 = self.timeout() t = self.running and t2 self.doIteration(t) except KeyboardInterrupt: self.stop() except: log.msg("Unexpected error in main loop.") log.deferr() else: log.msg('Main loop terminated.')
def _doWriteOrRead(self, selectable, fd, filter): try: if filter == EVFILT_READ: why = selectable.doRead() if filter == EVFILT_WRITE: why = selectable.doWrite() if not selectable.fileno() == fd: why = main.CONNECTION_LOST except: why = sys.exc_info()[1] log.deferr() if why: self.removeReader(selectable) self.removeWriter(selectable) selectable.connectionLost(failure.Failure(why))
def fireSystemEvent(self, eventType): """See twisted.internet.interfaces.IReactorCore.fireSystemEvent. """ sysEvtTriggers = self._eventTriggers.get(eventType) if not sysEvtTriggers: return defrList = [] for callable, args, kw in sysEvtTriggers[0]: try: d = callable(*args, **kw) except: log.deferr() else: if isinstance(d, Deferred): defrList.append(d) if defrList: DeferredList(defrList).addBoth(self._cbContinueSystemEvent, eventType) else: self.callLater(0, self._continueSystemEvent, eventType)
def _runWrite(self, fd): closed = 0 try: closed = fd.doWrite() except: closed = sys.exc_info()[1] log.deferr() if closed: self.removeReader(fd) self.removeWriter(fd) try: fd.connectionLost(failure.Failure(closed)) except: log.deferr() elif closed is None: return 1
def doRead(self): """Called when my socket is ready for reading.""" read = 0 while read < self.maxThroughput: try: data, addr = self.socket.recvfrom(self.maxPacketSize) read += len(data) self.protocol.datagramReceived(data) except socket.error, se: no = se.args[0] if no in (EAGAIN, EINTR, EWOULDBLOCK): return if (no == ECONNREFUSED) or (platformType == "win32" and no == WSAECONNRESET): self.protocol.connectionRefused() else: raise except: log.deferr()
def lineReceived(self, line): if self.inputHandler is not None: self.inputHandler(line) else: parts = line.strip().split() if len(parts): cmd, parts = parts[0].upper(), parts[1:] if cmd in NNTPServer.COMMANDS: func = getattr(self, 'do_%s' % cmd) try: func(*parts) except TypeError: self.sendLine('501 command syntax error') log.msg("501 command syntax error") log.msg("command was", line) log.deferr() except: self.sendLine('503 program fault - command not performed') log.msg("503 program fault") log.msg("command was", line) log.deferr() else: self.sendLine('500 command not recognized')
def proto_decache(self, objectID): """(internal) Decrement the reference count of a cached object. If the reference count is zero, free the reference, then send an 'uncached' directive. """ refs = self.remotelyCachedObjects[objectID].decref() # log.msg('decaching: %s #refs: %s' % (objectID, refs)) if refs == 0: lobj = self.remotelyCachedObjects[objectID] cacheable = lobj.object perspective = lobj.perspective # TODO: force_decache needs to be able to force-invalidate a # cacheable reference. try: cacheable.stoppedObserving(perspective, RemoteCacheObserver(self, cacheable, perspective)) except: log.deferr() puid = cacheable.processUniqueID() del self.remotelyCachedLUIDs[puid] del self.remotelyCachedObjects[objectID] self.sendCall("uncache", objectID)
def _doReadOrWrite(self, selectable, fd, event, POLLIN, POLLOUT, log, faildict=None): if not faildict: faildict = { error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()) } why = None inRead = False if event & POLL_DISCONNECTED and not (event & POLLIN): why = main.CONNECTION_LOST else: try: if event & POLLIN: why = selectable.doRead() inRead = True if not why and event & POLLOUT: why = selectable.doWrite() inRead = False if not selectable.fileno() == fd: why = error.ConnectionFdescWentAway('Filedescriptor went away') inRead = False except: log.deferr() why = sys.exc_info()[1] if why: self._disconnectSelectable(selectable, why, inRead)
def handleCommand(self, command, prefix, params): """ Determine the function to call for the given command and call it with the given arguments. @param command: The IRC command to determine the function for. @type command: L{bytes} @param prefix: The prefix of the IRC message (as returned by L{parsemsg}). @type prefix: L{bytes} @param params: A list of parameters to call the function with. @type params: L{list} """ method = getattr(self, "irc_%s" % command, None) try: if method is not None: method(prefix, params) else: self.irc_unknown(prefix, command, params) except: log.deferr()
def getApplication(config, passphrase): s = [(config[t], t) for t in ['python', 'source', 'file'] if config[t]][0] filename, style = s[0], {'file': 'pickle'}.get(s[1], s[1]) try: log.msg("Loading %s..." % filename) application = service.loadApplication(filename, style, passphrase) log.msg("Loaded.") except Exception as e: s = "Failed to load application: %s" % e if isinstance(e, KeyError) and e.args[0] == "application": s += """ Could not find 'application' in the file. To use 'twistd -y', your .tac file must create a suitable object (e.g., by calling service.Application()) and store it in a variable named 'application'. twistd loads your .tac file and scans the global variables for one of this name. Please read the 'Using Application' HOWTO for details. """ traceback.print_exc(file=log.logfile) log.msg(s) log.deferr() sys.exit('\n' + s + '\n') return application
def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType): if ans.lower() not in ('yes', 'no'): return deferredAskFrame("Please type 'yes' or 'no': ",1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType) if ans.lower() == 'no': frame.write('Host key verification failed.\r\n') raise error.ConchError('bad host key') try: frame.write( "Warning: Permanently added '%s' (%s) to the list of " "known hosts.\r\n" % (khHost, {b'ssh-dss':'DSA', b'ssh-rsa':'RSA'}[keyType])) with open(os.path.expanduser('~/.ssh/known_hosts'), 'a') as known_hosts: encodedKey = base64.encodestring(pubKey).replace(b'\n', b'') known_hosts.write('\n%s %s %s' % (khHost, keyType, encodedKey)) except: log.deferr() raise error.ConchError
def doConnect(): # log.deferr = handleError # HACK if '@' in options['host']: options['user'], options['host'] = options['host'].split('@',1) if not options.identitys: options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa'] host = options['host'] if not options['user']: options['user'] = getpass.getuser() if not options['port']: options['port'] = 22 else: options['port'] = int(options['port']) host = options['host'] port = options['port'] vhk = default.verifyHostKey if not options['host-key-algorithms']: options['host-key-algorithms'] = default.getHostKeyAlgorithms( host, options) uao = default.SSHUserAuthClient(options['user'], options, SSHConnection()) connect.connect(host, port, options, vhk, uao).addErrback(_ebExit)
def doRead(self): """ Called when my socket is ready for reading. """ read = 0 while read < self.maxThroughput: try: data, addr = self.socket.recvfrom(self.maxPacketSize) read += len(data) self.protocol.datagramReceived(data) except socket.error as se: no = se.args[0] if no in (EAGAIN, EINTR, EWOULDBLOCK): return if no == ECONNREFUSED: self.protocol.connectionRefused() else: raise except: log.deferr()
def proto_decache(self, objectID): """ (internal) Decrement the reference count of a cached object. If the reference count is zero, free the reference, then send an 'uncached' directive. @param objectID: The object ID. """ refs = self.remotelyCachedObjects[objectID].decref() # log.msg('decaching: %s #refs: %s' % (objectID, refs)) if refs == 0: lobj = self.remotelyCachedObjects[objectID] cacheable = lobj.object perspective = lobj.perspective # TODO: force_decache needs to be able to force-invalidate a # cacheable reference. try: cacheable.stoppedObserving(perspective, RemoteCacheObserver(self, cacheable, perspective)) except: log.deferr() puid = cacheable.processUniqueID() del self.remotelyCachedLUIDs[puid] del self.remotelyCachedObjects[objectID] self.sendCall(b"uncache", objectID)
def handleCommand(self, command, prefix, params): """Determine the function to call for the given command and call it with the given arguments. """ method = getattr(self, "irc_%s" % command, None) try: if method is not None: method(prefix, params) else: self.irc_unknown(prefix, command, params) except: log.deferr()
def removePID(pidfile): if not pidfile: return try: os.unlink(pidfile) except OSError, e: if e.errno == errno.EACCES or e.errno == errno.EPERM: log.msg("Warning: No permission to delete pid file") else: log.msg("Failed to unlink PID file:") log.deferr() except: log.msg("Failed to unlink PID file:") log.deferr()
def runWithProfiler(reactor, config): """Run reactor under standard profiler.""" try: import profile except ImportError, e: s = "Failed to import module profile: %s" % e s += """ This is most likely caused by your operating system not including profile.py due to it being non-free. Either do not use the option --profile, or install profile.py; your operating system vendor may provide it in a separate package. """ traceback.print_exc(file=log.logfile) log.msg(s) log.deferr() sys.exit('\n' + s + '\n') p = profile.Profile() p.runcall(reactor.run) if config['savestats']: p.dump_stats(config['profile']) else: # XXX - omfg python sucks tmp, sys.stdout = sys.stdout, open(config['profile'], 'a') p.print_stats() sys.stdout, tmp = tmp, sys.stdout tmp.close()
def _cbVerifyHostKey(self, ans, pubKey, khHost, keyType): if ans.lower() not in ('yes', 'no'): return deferredAskFrame("Please type 'yes' or 'no': ",1).addCallback(self._cbVerifyHostKey, pubKey, khHost, keyType) if ans.lower() == 'no': frame.write('Host key verification failed.\r\n') raise error.ConchError('bad host key') try: frame.write("Warning: Permanently added '%s' (%s) to the list of known hosts.\r\n" % (khHost, {'ssh-dss':'DSA', 'ssh-rsa':'RSA'}[keyType])) known_hosts = open(os.path.expanduser('~/.ssh/known_hosts'), 'a') encodedKey = base64.encodestring(pubKey).replace('\n', '') known_hosts.write('\n%s %s %s' % (khHost, keyType, encodedKey)) known_hosts.close() except: log.deferr() raise error.ConchError
def run(): options = GeneralOptions() try: options.parseOptions(sys.argv[1:]) except usage.UsageError, u: print 'ERROR: %s' % u options.opt_help() sys.exit(1) log.discardLogs() log.deferr = handleError # HACK if options['type']: if options['type'] == 'rsa': generateRSAkey(options) elif options['type'] == 'dsa': generateDSAkey(options) else: sys.exit('Key type was %s, must be one of: rsa, dsa' % options['type']) elif options['fingerprint']: printFingerprint(options) elif options['changepass']: changePassPhrase(options) elif options['showpub']: displayPublicKey(options) else: options.opt_help() sys.exit(1)
def request_exec(self, data): if not self.session: self.session = ISession(self.avatar) f,data = common.getNS(data) log.msg('executing command "%s"' % f) try: pp = SSHSessionProcessProtocol(self) self.session.execCommand(pp, f) except: log.deferr() return 0 else: self.client = pp return 1
def display(self, request): tm = [] flip = 0 namespace = {} self.prePresent(request) self.addVariables(namespace, request) # This variable may not be obscured... namespace['request'] = request namespace['self'] = self for elem in self.tmpl: flip = not flip if flip: if elem: tm.append(elem) else: try: x = eval(elem, namespace, namespace) except: log.deferr() tm.append(webutil.formatFailure(failure.Failure())) else: if isinstance(x, types.ListType): tm.extend(x) elif isinstance(x, Widget): val = x.display(request) if not isinstance(val, types.ListType): raise Exception("%s.display did not return a list, it returned %s!" % (x.__class__, repr(val))) tm.extend(val) else: # Only two allowed types here should be deferred and # string. tm.append(x) return tm
def _continueSystemEvent(self, eventType): sysEvtTriggers = self._eventTriggers.get(eventType) for callList in sysEvtTriggers[1], sysEvtTriggers[2]: for callable, args, kw in callList: try: callable(*args, **kw) except: log.deferr() # now that we've called all callbacks, no need to store # references to them anymore, in fact this can cause problems. del self._eventTriggers[eventType]
def _doReadOrWrite(self, source, condition, faildict={ error.ConnectionDone: failure.Failure(error.ConnectionDone()), error.ConnectionLost: failure.Failure(error.ConnectionLost()), }): why = None didRead = None if condition & POLL_DISCONNECTED and \ not (condition & gobject.IO_IN): why = main.CONNECTION_LOST else: try: if condition & gobject.IO_IN: why = source.doRead() didRead = source.doRead if not why and condition & gobject.IO_OUT: # if doRead caused connectionLost, don't call doWrite # if doRead is doWrite, don't call it again. if not source.disconnected and source.doWrite != didRead: why = source.doWrite() didRead = source.doWrite # if failed it was in write except: why = sys.exc_info()[1] log.msg('Error In %s' % source) log.deferr() if why: self._disconnectSelectable(source, why, didRead == source.doRead)
def _readAndWrite(self, source, condition): # note: gtk-1.2's gtk_input_add presents an API in terms of gdk # constants like INPUT_READ and INPUT_WRITE. Internally, it will add # POLL_HUP and POLL_ERR to the poll() events, but if they happen it # will turn them back into INPUT_READ and INPUT_WRITE. gdkevents.c # maps IN/HUP/ERR to INPUT_READ, and OUT/ERR to INPUT_WRITE. This # means there is no immediate way to detect a disconnected socket. # The g_io_add_watch() API is more suited to this task. I don't think # pygtk exposes it, though. why = None didRead = None try: if condition & gtk.GDK.INPUT_READ: why = source.doRead() didRead = source.doRead if not why and condition & gtk.GDK.INPUT_WRITE: # if doRead caused connectionLost, don't call doWrite # if doRead is doWrite, don't call it again. if not source.disconnected and source.doWrite != didRead: why = source.doWrite() didRead = source.doWrite # if failed it was in write except: why = sys.exc_info()[1] log.msg('Error In %s' % source) log.deferr() if why: self._disconnectSelectable(source, why, didRead == source.doRead)
def mainLoop(self): while self.running: try: while self.running: # Advance simulation time in delayed event # processors. self.runUntilCurrent() t2 = self.timeout() t = self.running and t2 self.doIteration(t) except: log.msg("Unexpected error in main loop.") log.deferr() else: log.msg('Main loop terminated.')
def connectionReady(self): """Initialize. Called after Banana negotiation is done. """ self.sendCall("version", self.version) for notifier in self.connects: try: notifier() except: log.deferr() self.connects = None if self.factory: # in tests we won't have factory self.factory.clientConnectionMade(self)