当前位置: 首页>>代码示例>>Python>>正文


Python tools.stderr函数代码示例

本文整理汇总了Python中willie.tools.stderr函数的典型用法代码示例。如果您正苦于以下问题:Python stderr函数的具体用法?Python stderr怎么用?Python stderr使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了stderr函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: error

    def error(self, origin=None, trigger=None):
        """Called internally when a module causes an error."""
        try:
            trace = traceback.format_exc()
            if sys.version_info.major < 3:
                trace = trace.decode('utf-8', errors='xmlcharrefreplace')
            stderr(trace)
            try:
                lines = list(reversed(trace.splitlines()))
                report = [lines[0].strip()]
                for line in lines:
                    line = line.strip()
                    if line.startswith('File "'):
                        report.append(line[0].lower() + line[1:])
                        break
                else:
                    report.append('source unknown')

                signature = '%s (%s)' % (report[0], report[1])
                # TODO: make not hardcoded
                log_filename = os.path.join(
                    self.config.logdir, 'exceptions.log'
                )
                with codecs.open(
                    log_filename, 'a', encoding='utf-8'
                ) as logfile:
                    logfile.write('Signature: %s\n' % signature)
                    if origin:
                        logfile.write(
                            'from %s at %s:\n' % (
                                origin.sender, str(datetime.now())
                            )
                        )
                    if trigger:
                        logfile.write(
                            'Message was: <%s> %s\n' % (
                                trigger.nick, trigger.group(0)
                            )
                        )
                    logfile.write(trace)
                    logfile.write(
                        '----------------------------------------\n\n'
                    )
            except Exception as e:
                stderr("Could not save full traceback!")
                self.debug(__file__, "(From: " + origin.sender +
                           "), can't save traceback: " + str(e), 'always')

            if origin:
                #self.msg(origin.sender, signature)
                # Don't send the file name 
                self.msg(origin.sender, report[0])
        except Exception as e:
            if origin:
                self.msg(origin.sender, "Got an error.")
                self.debug(
                    __file__,
                    "(From: " + origin.sender + ") " + str(e),
                    'always'
                )
开发者ID:antiman,项目名称:willie,代码行数:60,代码来源:irc.py

示例2: unregister

    def unregister(self, variables):
        """Unregister all willie callables in variables, and their bindings.

        When unloading a module, this ensures that the unloaded modules will
        not get called and that the objects can be garbage collected. Objects
        that have not been registered are ignored.

        Args:
        variables -- A list of callable objects from a willie module.

        """

        def remove_func(func, commands):
            """Remove all traces of func from commands."""
            for func_list in itervalues(commands):
                if func in func_list:
                    func_list.remove(func)

        hostmask = "%s!%[email protected]%s" % (self.nick, self.user, socket.gethostname())
        willie = self.WillieWrapper(self, irc.Origin(self, hostmask, [], {}))
        for obj in itervalues(variables):
            if obj in self.callables:
                self.callables.remove(obj)
                for commands in itervalues(self.commands):
                    remove_func(obj, commands)
            if obj in self.shutdown_methods:
                try:
                    obj(willie)
                except Exception as e:
                    stderr(
                        "Error calling shutdown method for module %s:%s" %
                        (obj.__module__, e)
                    )
                self.shutdown_methods.remove(obj)
开发者ID:Alhifar,项目名称:CGRelay,代码行数:34,代码来源:bot.py

示例3: handle_error

    def handle_error(self):
        """Handle any uncaptured error in the core.

        Overrides asyncore's handle_error.

        """
        trace = traceback.format_exc()
        stderr(trace)
        self.debug(
            __file__,
            'Fatal error in core, please review exception log',
            'always'
        )
        # TODO: make not hardcoded
        logfile = codecs.open(
            os.path.join(self.config.logdir, 'exceptions.log'),
            'a',
            encoding='utf-8'
        )
        logfile.write('Fatal error in core, handle_error() was called\n')
        logfile.write('last raw line was %s' % self.raw)
        logfile.write(trace)
        logfile.write('Buffer:\n')
        logfile.write(self.buffer)
        logfile.write('----------------------------------------\n\n')
        logfile.close()
        if self.error_count > 10:
            if (datetime.now() - self.last_error_timestamp).seconds < 5:
                print >> sys.stderr, "Too many errors, can't continue"
                os._exit(1)
        self.last_error_timestamp = datetime.now()
        self.error_count = self.error_count + 1
        if self.config.exit_on_error:
            os._exit(1)
开发者ID:Chiggins,项目名称:willie,代码行数:34,代码来源:irc.py

示例4: _modules

 def _modules(self):
     home = os.getcwd()
     modules_dir = os.path.join(home, 'modules')
     filenames = willie.loader.enumerate_modules(self)
     os.sys.path.insert(0, modules_dir)
     for name, mod_spec in iteritems(filenames):
         path, type_ = mod_spec
         try:
             module, _ = willie.loader.load_module(name, path, type_)
         except Exception as e:
             filename, lineno = willie.tools.get_raising_file_and_line()
             rel_path = os.path.relpath(filename, os.path.dirname(__file__))
             raising_stmt = "%s:%d" % (rel_path, lineno)
             stderr("Error loading %s: %s (%s)" % (name, e, raising_stmt))
         else:
             if hasattr(module, 'configure'):
                 prompt = name + ' module'
                 if module.__doc__:
                     doc = module.__doc__.split('\n', 1)[0]
                     if doc:
                         prompt = doc
                 prompt = 'Configure {} (y/n)? [n]'.format(prompt)
                 do_configure = get_input(prompt)
                 do_configure = do_configure and do_configure.lower() == 'y'
                 if do_configure:
                     module.configure(self)
     self.save()
开发者ID:Codered999,项目名称:willie,代码行数:27,代码来源:__init__.py

示例5: __init__

    def __init__(self, config):
        ca_certs = '/etc/pki/tls/cert.pem'
        if config.ca_certs is not None:
            ca_certs = config.ca_certs
        elif not os.path.isfile(ca_certs):
            ca_certs = '/etc/ssl/certs/ca-certificates.crt'
        if not os.path.isfile(ca_certs):
            stderr('Could not open CA certificates file. SSL will not '
                   'work properly.')

        if config.log_raw is None:
            # Default is to log raw data, can be disabled in config
            config.log_raw = True
        asynchat.async_chat.__init__(self)
        self.set_terminator(b'\n')
        self.buffer = ''

        self.nick = Nick(config.nick)
        """Willie's current ``Nick``. Changing this while Willie is running is
        untested."""
        self.user = config.user
        """Willie's user/ident."""
        self.name = config.name
        """Willie's "real name", as used for whois."""

        self.channels = []
        """The list of channels Willie is currently in."""

        self.stack = {}
        self.ca_certs = ca_certs
        self.hasquit = False

        self.sending = threading.RLock()
        self.writing_lock = threading.Lock()
        self.raw = None

        # Right now, only accounting for two op levels.
        # This might be expanded later.
        # These lists are filled in startup.py, as of right now.
        self.ops = dict()
        """
        A dictionary mapping channels to a ``Nick`` list of their operators.
        """
        self.halfplus = dict()
        """
        A dictionary mapping channels to a ``Nick`` list of their half-ops and
        ops.
        """
        self.voices = dict()
        """
        A dictionary mapping channels to a ``Nick`` list of their voices,
        half-ops and ops.
        """

        # We need this to prevent error loops in handle_error
        self.error_count = 0

        self.connection_registered = False
        """ Set to True when a server has accepted the client connection and
开发者ID:DavidAdamczyk,项目名称:willie,代码行数:59,代码来源:irc.py

示例6: _timeout_check

 def _timeout_check(self):
     while self.connected or self.connecting:
         if (datetime.now() - self.last_ping_time).seconds > int(self.config.timeout):
             stderr('Ping timeout reached after %s seconds, closing connection' % self.config.timeout)
             self.handle_close()
             break
         else:
             time.sleep(int(self.config.timeout))
开发者ID:Chiggins,项目名称:willie,代码行数:8,代码来源:irc.py

示例7: handle_close

    def handle_close(self):
        self.connection_registered = False

        self._shutdown()
        stderr('Closed!')

        # This will eventually call asyncore dispatchers close method, which
        # will release the main thread. This should be called last to avoid
        # race conditions.
        self.close()
开发者ID:Chiggins,项目名称:willie,代码行数:10,代码来源:irc.py

示例8: run

def run(config):
    if config.core.delay is not None:
        delay = config.core.delay
    elif config.core.timeout is not None:
        delay = 2 * int(config.core.timeout)
    else:
        delay = 300
    # Inject ca_certs from config to web for SSL validation of web requests
    if hasattr(config, 'ca_certs') and config.ca_certs is not None:
        web.ca_certs  = config.ca_certs
    else:
        web.ca_certs = '/etc/pki/tls/certs/ca-bundle.crt'

    def signal_handler(sig, frame):
        if sig == signal.SIGUSR1 or sig == signal.SIGTERM:
            stderr('Got quit signal, shutting down.')
            p.quit('Closing')
    while True:
        try:
            p = bot.Willie(config)
            if hasattr(signal, 'SIGUSR1'):
                signal.signal(signal.SIGUSR1, signal_handler)
            if hasattr(signal, 'SIGTERM'):
                signal.signal(signal.SIGTERM, signal_handler)
            p.run(config.core.host, int(config.core.port))
        except KeyboardInterrupt:
            break
        except Exception as e:
            trace = traceback.format_exc()
            try:
                stderr(trace)
            except:
                pass
            logfile = open(os.path.join(config.logdir, 'exceptions.log'), 'a')
            logfile.write('Critical exception in core')
            logfile.write(trace)
            logfile.write('----------------------------------------\n\n')
            logfile.close()
            os.unlink(config.pid_file_path)
            os._exit(1)

        if not isinstance(delay, int):
            break
        if p.hasquit or config.exit_on_error:
            break
        stderr('Warning: Disconnected. Reconnecting in %s seconds...' % delay)
        time.sleep(delay)
    os.unlink(config.pid_file_path)
    os._exit(0)
开发者ID:antiman,项目名称:willie,代码行数:49,代码来源:__init__.py

示例9: initiate_connect

 def initiate_connect(self, host, port):
     stderr("Connecting to %s:%s..." % (host, port))
     source_address = (self.config.core.bind_host, 0) if self.config.core.bind_address else None
     self.set_socket(socket.create_connection((host, port), source_address=source_address))
     if self.config.core.use_ssl and has_ssl:
         self.send = self._ssl_send
         self.recv = self._ssl_recv
     elif not has_ssl and self.config.core.use_ssl:
         stderr("SSL is not avilable on your system, attempting connection " "without it")
     self.connect((host, port))
     try:
         asyncore.loop()
     except KeyboardInterrupt:
         print("KeyboardInterrupt")
         self.quit("KeyboardInterrupt")
开发者ID:kqzi,项目名称:willie,代码行数:15,代码来源:irc.py

示例10: found_terminator

    def found_terminator(self):
        line = self.buffer
        if line.endswith('\r'):
            line = line[:-1]
        self.buffer = ''
        pretrigger = PreTrigger(self.nick, line)

        if pretrigger.args[0] == 'PING':
            self.write(('PONG', pretrigger.args[-1]))
        elif pretrigger.args[0] == 'ERROR':
            self.debug(__file__, pretrigger.args[-1], 'always')
            if self.hasquit:
                self.close_when_done()
        elif pretrigger.args[0] == '433':
            stderr('Nickname already in use!')
            self.handle_close()

        self.dispatch(pretrigger)
开发者ID:dkg,项目名称:willie,代码行数:18,代码来源:irc.py

示例11: found_terminator

    def found_terminator(self):
        line = self.buffer
        if line.endswith("\r"):
            line = line[:-1]
        self.buffer = ""
        self.raw = line

        # Break off IRCv3 message tags, if present
        tags = {}
        if line.startswith("@"):
            tagstring, line = line.split(" ", 1)
            for tag in tagstring[1:].split(";"):
                tag = tag.split("=", 1)
                if len(tag) > 1:
                    tags[tag[0]] = tag[1]
                else:
                    tags[tag[0]] = None

        if line.startswith(":"):
            source, line = line[1:].split(" ", 1)
        else:
            source = None

        if " :" in line:
            argstr, text = line.split(" :", 1)
            args = argstr.split(" ")
            args.append(text)
        else:
            args = line.split(" ")
            text = args[-1]

        self.last_ping_time = datetime.now()
        if args[0] == "PING":
            self.write(("PONG", text))
        elif args[0] == "ERROR":
            self.debug(__file__, text, "always")
            if self.hasquit:
                self.close_when_done()
        elif args[0] == "433":
            stderr("Nickname already in use!")
            self.handle_close()

        origin = Origin(self, source, args, tags)
        self.dispatch(origin, text, args)
开发者ID:kqzi,项目名称:willie,代码行数:44,代码来源:irc.py

示例12: found_terminator

    def found_terminator(self):
        line = self.buffer
        if line.endswith('\r'):
            line = line[:-1]
        self.buffer = ''
        self.raw = line

        # Break off IRCv3 message tags, if present
        tags = {}
        if line.startswith('@'):
            tagstring, line = line.split(' ', 1)
            for tag in tagstring[1:].split(';'):
                tag = tag.split('=', 1)
                if len(tag) > 1:
                    tags[tag[0]] = tag[1]
                else:
                    tags[tag[0]] = None

        if line.startswith(':'):
            source, line = line[1:].split(' ', 1)
        else:
            source = None

        if ' :' in line:
            argstr, text = line.split(' :', 1)
            args = argstr.split(' ')
            args.append(text)
        else:
            args = line.split(' ')
            text = args[-1]

        self.last_ping_time = datetime.now()
        if args[0] == 'PING':
            self.write(('PONG', text))
        elif args[0] == 'ERROR':
            self.debug(__file__, text, 'always')
            if self.hasquit:
                self.close_when_done()
        elif args[0] == '433':
            stderr('Nickname already in use!')
            self.handle_close()

        origin = Origin(self, source, args, tags)
        self.dispatch(origin, text, args)
开发者ID:Chiggins,项目名称:willie,代码行数:44,代码来源:irc.py

示例13: found_terminator

    def found_terminator(self):
        line = self.buffer
        if line.endswith('\r'):
            line = line[:-1]
        self.buffer = ''
        self.last_ping_time = datetime.now()
        pretrigger = PreTrigger(self.nick, line)

        if pretrigger.event == 'PING':
            self.write(('PONG', pretrigger.args[-1]))
        elif pretrigger.event == 'ERROR':
            LOGGER.error("ERROR recieved from server: %s", pretrigger.args[-1])
            if self.hasquit:
                self.close_when_done()
        elif pretrigger.event == '433':
            stderr('Nickname already in use!')
            self.handle_close()

        self.dispatch(pretrigger)
开发者ID:Cadair,项目名称:willie,代码行数:19,代码来源:irc.py

示例14: error

    def error(self, trigger=None):
        """Called internally when a module causes an error."""
        try:
            trace = traceback.format_exc()
            if sys.version_info.major < 3:
                trace = trace.decode('utf-8', errors='xmlcharrefreplace')
            stderr(trace)
            try:
                lines = list(reversed(trace.splitlines()))
                report = [lines[0].strip()]
                for line in lines:
                    line = line.strip()
                    if line.startswith('File "'):
                        report.append(line[0].lower() + line[1:])
                        break
                else:
                    report.append('source unknown')

                signature = '%s (%s)' % (report[0], report[1])
                # TODO: make not hardcoded
                log_filename = os.path.join(self.config.logdir, 'exceptions.log')
                with codecs.open(log_filename, 'a', encoding='utf-8') as logfile:
                    logfile.write('Signature: %s\n' % signature)
                    if trigger:
                        logfile.write('from {} at {}. Message was: {}\n'.format(
                            trigger.nick, str(datetime.now()), trigger.group(0)))
                    logfile.write(trace)
                    logfile.write(
                        '----------------------------------------\n\n'
                    )
            except Exception as e:
                stderr("Could not save full traceback!")
                LOGGER.error("Could not save traceback from %s to file: %s", trigger.sender, str(e))

            if trigger:
                #self.msg(trigger.sender, signature)
				self.msg(trigger.sender, "I\'m afraid I can\'t do that.")
				print(signature)
        except Exception as e:
            if trigger:
                self.msg(trigger.sender, "Got an error.")
                LOGGER.error("Exception from %s: %s", trigger.sender, str(e))
开发者ID:Oracizan,项目名称:ATM,代码行数:42,代码来源:irc.py

示例15: _shutdown

    def _shutdown(self):
        stderr(
            'Calling shutdown for %d modules.' % (len(self.shutdown_methods),)
        )

        for moduleName in self.config.enumerate_modules():
            module = sys.modules[moduleName]
            if hasattr(module, "shutdown"):
                module.shutdown(self)

        hostmask = "%s!%[email protected]%s" % (self.nick, self.user, socket.gethostname())
        willie = self.WillieWrapper(self, irc.Origin(self, hostmask, [], {}))
        for shutdown_method in self.shutdown_methods:
            try:
                stderr(
                    "calling %s.%s" % (
                        shutdown_method.__module__, shutdown_method.__name__,
                    )
                )
                shutdown_method(willie)
            except Exception as e:
                stderr(
                    "Error calling shutdown method for module %s:%s" % (
                        shutdown_method.__module__, e
                    )
                )
开发者ID:antiman,项目名称:willie,代码行数:26,代码来源:bot.py


注:本文中的willie.tools.stderr函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。