• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python tools.stderr函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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


示例16: handle_connect

    def handle_connect(self):
        if self.config.core.use_ssl and has_ssl:
            if not self.config.core.verify_ssl:
                self.ssl = ssl.wrap_socket(self.socket,
                                           do_handshake_on_connect=True,
                                           suppress_ragged_eofs=True)
            else:
                self.ssl = ssl.wrap_socket(self.socket,
                                           do_handshake_on_connect=True,
                                           suppress_ragged_eofs=True,
                                           cert_reqs=ssl.CERT_REQUIRED,
                                           ca_certs=self.ca_certs)
                try:
                    ssl.match_hostname(self.ssl.getpeercert(), self.config.host)
                except ssl.CertificateError:
                    stderr("Invalid certficate, hostname mismatch!")
                    os.unlink(self.config.pid_file_path)
                    os._exit(1)
            self.set_socket(self.ssl)

        if self.config.core.server_password is not None:
            self.write(('PASS', self.config.core.server_password))
        self.write(('NICK', self.nick))
        self.write(('USER', self.user, '+iw', self.nick), self.name)

        stderr('Connected.')
        self.last_ping_time = datetime.now()
        timeout_check_thread = threading.Thread(target=self._timeout_check)
        timeout_check_thread.start()
        ping_thread = threading.Thread(target=self._send_ping)
        ping_thread.start()

        # Request list of server capabilities. IRCv3 servers will respond with
        # CAP * LS (which we handle in coretasks). v2 servers will respond with
        # 421 Unknown command, which we'll ignore
        # This needs to come after Authentication as it can cause connection
        # Issues
        self.write(('CAP', 'LS'))
开发者ID:Khabi,项目名称:willie,代码行数:38,代码来源:irc.py


示例17: _shutdown

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

        for shutdown_method in self.shutdown_methods:
            try:
                stderr("calling %s.%s" % (shutdown_method.__module__, shutdown_method.__name__))
                shutdown_method(self)
            except Exception as e:
                stderr("Error calling shutdown method for module %s:%s" % (shutdown_method.__module__, e))
开发者ID:Codered999,项目名称:willie,代码行数:9,代码来源:bot.py


示例18: run

def run(config):
    import willie.bot as bot
    import willie.web as web
    from willie.tools import stderr

    if config.core.delay is not None:
        delay = config.core.delay
    else:
        delay = 20
    # Inject ca_certs from config to web for SSL validation of web requests
    web.ca_certs = "/etc/pki/tls/certs/ca-bundle.crt"
    if hasattr(config, "ca_certs") and config.ca_certs is not None:
        web.ca_certs = config.ca_certs
    elif not os.path.isfile(web.ca_certs):
        web.ca_certs = "/etc/ssl/certs/ca-certificates.crt"
    if not os.path.isfile(web.ca_certs):
        stderr("Could not open CA certificates file. SSL will not " "work properly.")

    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:kamilla,项目名称:jambot,代码行数:55,代码来源:__init__.py


示例19: log_raw

    def log_raw(self, line, prefix):
        """Log raw line to the raw log."""
        if not self.config.core.log_raw:
            return
        if not os.path.isdir(self.config.core.logdir):
            try:
                os.mkdir(self.config.core.logdir)
            except Exception as e:
                stderr('There was a problem creating the logs directory.')
                stderr('%s %s' % (str(e.__class__), str(e)))
                stderr('Please fix this and then run Willie again.')
                os._exit(1)
        f = codecs.open(os.path.join(self.config.core.logdir, 'raw.log'),
                        'a', encoding='utf-8')
        f.write(prefix + unicode(time.time()) + "\t")
        temp = line.replace('\n', '')

        f.write(temp)
        f.write("\n")
        f.close()
开发者ID:ToTV,项目名称:willie,代码行数:20,代码来源:irc.py


示例20: _shutdown

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

        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:Alhifar,项目名称:CGRelay,代码行数:21,代码来源:bot.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python tools.Nick类代码示例发布时间:2022-05-26
下一篇:
Python tools.itervalues函数代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap