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


Python tools.stderr函数代码示例

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


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

示例1: handle_init

def handle_init(options):
    """Use config wizard to initialize a new configuration file for the bot

    :param options: parsed arguments
    :type options: ``argparse.Namespace``

    .. note::

       Due to how the config wizard works, the configuration filename's
       extension **must be** ``.cfg``.

    """
    config_filename = utils.find_config(
        config.DEFAULT_HOMEDIR,
        getattr(options, 'config', None) or 'default')
    config_name, ext = os.path.splitext(config_filename)

    if ext and ext != '.cfg':
        tools.stderr('Configuration wizard accepts .cfg files only')
        return 1
    elif not ext:
        config_filename = config_name + '.cfg'

    if os.path.isfile(config_filename):
        tools.stderr('Configuration file %s already exists' % config_filename)
        return 1

    print('Starting Sopel config wizard for: %s' % config_filename)
    config._wizard('all', config_name)
开发者ID:neonobjclash,项目名称:sopel,代码行数:29,代码来源:config.py

示例2: handle_error

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

        Overrides asyncore's handle_error.

        """
        trace = traceback.format_exc()
        stderr(trace)
        LOGGER.error('Fatal error in core, please review exception log')
        # TODO: make not hardcoded
        logfile = codecs.open(
            os.path.join(self.config.core.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
开发者ID:ctburley,项目名称:sopel,代码行数:28,代码来源:irc.py

示例3: _modules

 def _modules(self):
     home = os.getcwd()
     modules_dir = os.path.join(home, 'modules')
     filenames = sopel.loader.enumerate_modules(self)
     os.sys.path.insert(0, modules_dir)
     for name, mod_spec in iteritems(filenames):
         path, type_ = mod_spec
         try:
             module, _ = sopel.loader.load_module(name, path, type_)
         except Exception as e:
             filename, lineno = sopel.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:daniellawrence,项目名称:sopel,代码行数:27,代码来源:__init__.py

示例4: signal_handler

 def signal_handler(sig, frame):
     if sig == signal.SIGUSR1 or sig == signal.SIGTERM or sig == signal.SIGINT:
         tools.stderr('Got quit signal, shutting down.')
         p.quit('Closing')
     elif sig == signal.SIGUSR2 or sig == signal.SIGILL:
         tools.stderr('Got restart signal.')
         p.restart('Restarting')
开发者ID:sopel-irc,项目名称:sopel,代码行数:7,代码来源:run.py

示例5: _timeout_check

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

示例6: reload_module_tree

def reload_module_tree(bot, name, seen=None, silent=False):
    from types import ModuleType

    old_module = sys.modules[name]

    if seen is None:
        seen = {}
    if name not in seen:
        seen[name] = []

    old_callables = {}
    for obj_name, obj in iteritems(vars(old_module)):
        if callable(obj):
            if (getattr(obj, '__name__', None) == 'shutdown' and
                        obj in bot.shutdown_methods):
                # If this is a shutdown method, call it first.
                try:
                    stderr(
                        "calling %s.%s" % (
                            obj.__module__, obj.__name__,
                        )
                    )
                    obj(bot)
                except Exception as e:
                    stderr(
                        "Error calling shutdown method for module %s:%s" % (
                            obj.__module__, e
                        )
                    )
            bot.unregister(obj)
        elif (type(obj) is ModuleType and
              obj.__name__.startswith(name + '.') and
              obj.__name__ not in sys.builtin_module_names):
            # recurse into submodules, see issue 1056
            if obj not in seen[name]:
                seen[name].append(obj)
                reload(obj)
                reload_module_tree(bot, obj.__name__, seen, silent)

    modules = sopel.loader.enumerate_modules(bot.config)
    if name not in modules:
        return  # Only reload the top-level module, once recursion is finished

    # Also remove all references to sopel callables from top level of the
    # module, so that they will not get loaded again if reloading the
    # module does not override them.
    for obj_name in old_callables.keys():
        delattr(old_module, obj_name)

    # Also delete the setup function
    # Sub-modules shouldn't have setup functions, so do after the recursion check
    if hasattr(old_module, "setup"):
        delattr(old_module, "setup")

    path, type_ = modules[name]
    load_module(bot, name, path, type_, silent)
开发者ID:neonobjclash,项目名称:sopel,代码行数:56,代码来源:reload.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:ctburley,项目名称:sopel,代码行数:10,代码来源:irc.py

示例8: wizard

def wizard(filename):
    """Global Configuration Wizard

    :param str filename: name of the new file to be created
    :return: the created configuration object

    This wizard function helps the creation of a Sopel configuration file,
    with its core section and its plugins' sections.
    """
    homedir, basename = os.path.split(filename)
    if not basename:
        raise config.ConfigurationError(
            'Sopel requires a filename for its configuration, not a directory')

    try:
        if not os.path.isdir(homedir):
            print('Creating config directory at {}'.format(homedir))
            os.makedirs(homedir)
            print('Config directory created')
    except Exception:
        tools.stderr('There was a problem creating {}'.format(homedir))
        raise

    name, ext = os.path.splitext(basename)
    if not ext:
        # Always add .cfg if filename does not have an extension
        filename = os.path.join(homedir, name + '.cfg')
    elif ext != '.cfg':
        # It is possible to use a non-cfg file for Sopel
        # but the wizard does not allow it at the moment
        raise config.ConfigurationError(
            'Sopel uses ".cfg" as configuration file extension, not "%s".' % ext)

    settings = config.Config(filename, validate=False)

    print("Please answer the following questions "
          "to create your configuration file (%s):\n" % filename)
    config.core_section.configure(settings)
    if settings.option(
        'Would you like to see if there are any modules '
        'that need configuring'
    ):
        _plugins_wizard(settings)

    try:
        settings.save()
    except Exception:  # TODO: Be specific
        tools.stderr("Encountered an error while writing the config file. "
                     "This shouldn't happen. Check permissions.")
        raise

    print("Config file written successfully!")
    return settings
开发者ID:sopel-irc,项目名称:sopel,代码行数:53,代码来源:utils.py

示例9: command_restart

def command_restart(opts):
    """Restart a running Sopel instance"""
    # Get Configuration
    try:
        settings = utils.load_settings(opts)
    except config.ConfigurationNotFound as error:
        tools.stderr('Configuration "%s" not found' % error.filename)
        return ERR_CODE

    if settings.core.not_configured:
        tools.stderr('Sopel is not configured, can\'t stop')
        return ERR_CODE

    # Redirect Outputs
    utils.redirect_outputs(settings, opts.quiet)

    # Get Sopel's PID
    filename = get_pid_filename(opts, settings.core.pid_dir)
    pid = get_running_pid(filename)

    if pid is None or not tools.check_pid(pid):
        tools.stderr('Sopel is not running!')
        return ERR_CODE

    tools.stderr('Asking Sopel to restart')
    if hasattr(signal, 'SIGUSR2'):
        os.kill(pid, signal.SIGUSR2)
    else:
        # Windows will not generate SIGILL itself
        # https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/signal
        os.kill(pid, signal.SIGILL)
开发者ID:sopel-irc,项目名称:sopel,代码行数:31,代码来源:run.py

示例10: _load

def _load(bot, plugin):
    # handle errors while loading (if any)
    try:
        plugin.load()
        if plugin.has_setup():
            plugin.setup(bot)
        plugin.register(bot)
    except Exception as e:
        filename, lineno = tools.get_raising_file_and_line()
        rel_path = os.path.relpath(filename, os.path.dirname(__file__))
        raising_stmt = "%s:%d" % (rel_path, lineno)
        tools.stderr(
            "Error loading %s: %s (%s)" % (plugin.name, e, raising_stmt))
        raise
开发者ID:sopel-irc,项目名称:sopel,代码行数:14,代码来源:reload.py

示例11: _plugins_wizard

def _plugins_wizard(settings):
    usable_plugins = plugins.get_usable_plugins(settings)
    for plugin, is_enabled in usable_plugins.values():
        if not is_enabled:
            # Do not configure non-enabled modules
            continue

        name = plugin.name
        try:
            _plugin_wizard(settings, plugin)
        except Exception as e:
            filename, lineno = tools.get_raising_file_and_line()
            rel_path = os.path.relpath(filename, os.path.dirname(__file__))
            raising_stmt = "%s:%d" % (rel_path, lineno)
            tools.stderr("Error loading %s: %s (%s)" % (name, e, raising_stmt))
开发者ID:sopel-irc,项目名称:sopel,代码行数:15,代码来源:utils.py

示例12: 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_host 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:calzoneman,项目名称:sopel,代码行数:15,代码来源:irc.py

示例13: 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.core.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 and self.config.core.reply_errors and trigger.sender is not None:
                self.msg(trigger.sender, signature)
            if trigger:
                LOGGER.error("Exception from {}: {} ({})".format(trigger.sender, str(signature), trigger.raw))
        except Exception as e:
            if trigger and self.config.core.reply_errors and trigger.sender is not None:
                self.msg(trigger.sender, "Got an error.")
            if trigger:
                LOGGER.error("Exception from {}: {} ({})".format(trigger.sender, str(e), trigger.raw))
开发者ID:calzoneman,项目名称:sopel,代码行数:44,代码来源:irc.py

示例14: 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:ctburley,项目名称:sopel,代码行数:19,代码来源:irc.py

示例15: check_not_root

def check_not_root():
    """Check if root is running the bot.

    It raises a ``RuntimeError`` if the user has root privileges on Linux or
    if it is the ``Administrator`` account on Windows.
    """
    opersystem = platform.system()
    if opersystem in ["Linux", "Darwin"]:
        # Linux/Mac
        if os.getuid() == 0 or os.geteuid() == 0:
            raise RuntimeError('Error: Do not run Sopel with root privileges.')
    elif opersystem in ["Windows"]:
        # Windows
        if os.environ.get("USERNAME") == "Administrator":
            raise RuntimeError('Error: Do not run Sopel as Administrator.')
    else:
        tools.stderr(
            "Warning: %s is an uncommon operating system platform. "
            "Sopel should still work, but please contact Sopel's developers "
            "if you experience issues."
            % opersystem)
开发者ID:sopel-irc,项目名称:sopel,代码行数:21,代码来源:run.py


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