Python warnings 模块,formatwarning() 实例源码

我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用warnings.formatwarning()

项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:abusehelper    作者:Exploit-install    | 项目源码 | 文件源码
def execute(self):
        def showwarning(message, category, filename, fileno, file=None, line=None):
            msg = warnings.formatwarning(message, category, filename, fileno, line)
            self.log.warning(msg.strip())

        with warnings.catch_warnings():
            warnings.simplefilter("always")
            warnings.showwarning = showwarning

            try:
                return self.run()
            except SystemExit:
                raise
            except:
                self.log.critical(traceback.format_exc().strip())
                sys.exit(1)
项目:hostapd-mana    作者:adde88    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:pyextinction    作者:mfouesneau    | 项目源码 | 文件源码
def missing_units_warning(name, defaultunit):
    """ Warn if any unit is missing

    Parameters
    ----------
    name: str
        name of the variable

    defaultunit: str
        default unit definition

    Raises
    ------
    warning: warnings.warn
        warn if units are assumed
    """
    warnings.formatwarning = warning_on_one_line
    msg = 'Variable {0:s} does not have explicit units. Assuming `{1:s}`\n'
    # stacklevel makes the correct code reference
    warnings.warn(msg.format(name, defaultunit), stacklevel=4)
项目:Intranet-Penetration    作者:yuxiaokui    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:MKFQ    作者:maojingios    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:boartty    作者:openstack    | 项目源码 | 文件源码
def _showWarning(self, message, category, filename, lineno,
                     file=None, line=None):
        # Don't display repeat warnings
        if str(message) in self.logged_warnings:
            return
        m = warnings.formatwarning(message, category, filename, lineno, line)
        self.log.warning(m)
        self.logged_warnings.add(str(message))
        # Log this warning, but never display it to the user; it is
        # nearly un-actionable.
        if category == requestsexceptions.InsecurePlatformWarning:
            return
        if category == requestsexceptions.SNIMissingWarning:
            return
        # Disable InsecureRequestWarning when certificate validation is disabled
        if not self.config.verify_ssl:
            if category == requestsexceptions.InsecureRequestWarning:
                return
        self.error_queue.put(('Warning', m))
        os.write(self.error_pipe, six.b('error\n'))
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:sslstrip-hsts-openwrt    作者:adde88    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:xxNet    作者:drzorm    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:empyrion-python-api    作者:huhlig    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:pmatic    作者:LarsMichelsen    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:Docker-XX-Net    作者:kuanghy    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Implementation of showwarnings which redirects to logging, which will first
    check to see if the file parameter is None. If a file is specified, it will
    delegate to the original warnings implementation of showwarning. Otherwise,
    it will call warnings.formatwarning and will log the resulting string to a
    warnings logger named "py.warnings" with level logging.WARNING.
    """
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno, line)
        logger = getLogger("py.warnings")
        if not logger.handlers:
            logger.addHandler(NullHandler())
        logger.warning("%s", s)
项目:BreezyCreate2    作者:simondlevy    | 项目源码 | 文件源码
def play_note(self,note_name,note_duration):
        """Plays a single note by creating a 1 note song in song 0
        """
        current_song = 0
        play_list=[]
        noError = True
        if noError:
            #Need to map ascii to numbers from the dict.

            if note_name in self.config.data['midi table']:
                play_list.append(self.config.data['midi table'][note_name])
                play_list.append(note_duration)
            else:
                # That note doesn't exist. Plays nothing
                # Raise an error so the software knows that the input was bad
                play_list.append(self.config.data['midi table'][0])
                warnings.formatwarning = custom_format_warning
                warnings.warn("Warning: Note '" + note_name + "' was not found in midi table")
            #create a song from play_list and play it
            self.create_song(current_song,play_list)
            self.play(current_song)
项目:python-application    作者:AGProjects    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    if file is not None:
        _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        _warning_logger.warning(warnings.formatwarning(message, category, filename, lineno, line).rstrip('\n'))
项目:psyplot    作者:Chilipp    | 项目源码 | 文件源码
def customwarn(message, category, filename, lineno, *args, **kwargs):
    """Use the psyplot.warning logger for categories being out of
    PsyPlotWarning and PsyPlotCritical and the default warnings.showwarning
    function for all the others."""
    if category is PsyPlotWarning:
        logger.warning(warnings.formatwarning(
            "\n%s" % message, category, filename, lineno))
    elif category is PsyPlotCritical:
        logger.critical(warnings.formatwarning(
            "\n%s" % message, category, filename, lineno),
            exc_info=True)
    else:
        old_showwarning(message, category, filename, lineno, *args, **kwargs)
项目:uncover-ml    作者:GeoscienceAustralia    | 项目源码 | 文件源码
def warn_with_traceback(message, category, filename, lineno, line=None):
    """
    copied from:
    http://stackoverflow.com/questions/22373927/get-traceback-of-warnings
    """
    traceback.print_stack()
    log = sys.stderr
    log.write(warnings.formatwarning(
        message, category, filename, lineno, line))
项目:isar    作者:ilbers    | 项目源码 | 文件源码
def _showwarning(message, category, filename, lineno, file=None, line=None):
    if file is not None:
        if _warnings_showwarning is not None:
            _warnings_showwarning(message, category, filename, lineno, file, line)
    else:
        s = warnings.formatwarning(message, category, filename, lineno)
        warnlog.warning(s)
项目:qiime2    作者:qiime2    | 项目源码 | 文件源码
def warning():
    def _warnformat(msg, category, filename, lineno, file=None, line=None):
        return '%s:%s: %s: %s\n' % (filename, lineno, category.__name__, msg)

    default_warn_format = warnings.formatwarning
    try:
        warnings.formatwarning = _warnformat
        yield warnings.warn
    finally:
        warnings.formatwarning = default_warn_format


# Descriptor protocol for creating an attribute that is bound to an
# (arbitrarily nested) attribute accessible to the instance at runtime.
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def idle_showwarning(message, category, filename, lineno,
                         file=None, line=None):
        if file is None:
            file = warning_stream
        try:
            file.write(warnings.formatwarning(message, category, filename,
                                              lineno, line=line))
        except IOError:
            pass  ## file (probably __stderr__) is invalid, warning dropped.
项目:fandango    作者:tango-controls    | 项目源码 | 文件源码
def deprecated(self, msg, *args, **kw):
        filename, lineno, func = self.log_obj.findCaller()
        depr_msg = warnings.formatwarning(
          msg, DeprecationWarning, filename, lineno)
        self.log_obj.warning(depr_msg, *args, **kw)
项目:hydpy    作者:tyralla    | 项目源码 | 文件源码
def customwarn(message, category, filename, lineno, file=None, line=None):
    sys.stdout.write(warnings.formatwarning(
                                    message, category, filename, lineno))
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def customwarn(message, category, filename, lineno, file=None, line=None):
    #sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))
    log.warning(str(category.__name__) + ": " + str(message) + " [file:" + str(filename) + ", line:" + str(lineno) + "]")
项目:CAAPR    作者:Stargrazer82301    | 项目源码 | 文件源码
def customwarn(message, category, filename, lineno, file=None, line=None):
    #sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))
    log.warning(str(category.__name__) + ": " + str(message) + " [file:" + str(filename) + ", line:" + str(lineno) + "]")
项目:marketcrush    作者:basaks    | 项目源码 | 文件源码
def warn_with_traceback(message, category, filename, lineno, line=None):
    """
    copied from:
    http://stackoverflow.com/questions/22373927/get-traceback-of-warnings
    """
    traceback.print_stack()
    log = sys.stderr
    log.write(warnings.formatwarning(
        message, category, filename, lineno, line))
项目:PyNIT    作者:dvm-shlee    | 项目源码 | 文件源码
def deprecated():
        warnings.formatwarning = Warning.warning_on_one_line
        warnings.simplefilter("default")
        warnings.warn("pynit.Preprocess() will be deprecated soon. Please use pynit.Process() instead.", DeprecationWarning,
                      stacklevel=2)
        warnings.simplefilter("ignore")
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def __call__(self):
        """Run all check_* methods."""
        if self.on:
            oldformatwarning = warnings.formatwarning
            warnings.formatwarning = self.formatwarning
            try:
                for name in dir(self):
                    if name.startswith('check_'):
                        method = getattr(self, name)
                        if method and hasattr(method, '__call__'):
                            method()
            finally:
                warnings.formatwarning = oldformatwarning
项目:autosub-bootstrapbill    作者:BenjV    | 项目源码 | 文件源码
def formatwarning(self, message, category, filename, lineno, line=None):
        """Function to format a warning."""
        return 'CherryPy Checker:\n%s\n\n' % message

    # This value should be set inside _cpconfig.
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def idle_showwarning(message, category, filename, lineno,
                         file=None, line=None):
        if file is None:
            file = warning_stream
        try:
            file.write(warnings.formatwarning(message, category, filename,
                                              lineno, line=line))
        except IOError:
            pass  ## file (probably __stderr__) is invalid, warning dropped.
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
    traceback.print_stack()
    log = file if hasattr(file,'write') else sys.stderr
    log.write(warnings.formatwarning(message, category, filename, lineno, line))
项目:Python-iBeacon-Scan    作者:NikNitro    | 项目源码 | 文件源码
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
    traceback.print_stack()
    log = file if hasattr(file, 'write') else sys.stderr
    log.write(warnings.formatwarning(message, category, filename, lineno, line))
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_filteredOnceWarning(self):
        """
        L{deprecate.warnAboutFunction} emits a warning that will be filtered
        once if L{warnings.filterwarning} is called with the module name of the
        deprecated function and an action of once.
        """
        # Clean up anything *else* that might spuriously filter out the warning,
        # such as the "always" simplefilter set up by unittest._collectWarnings.
        # We'll also rely on trial to restore the original filters afterwards.
        del warnings.filters[:]

        warnings.filterwarnings(
            action="module", module="twisted_private_helper")

        from twisted_private_helper import module
        module.callTestFunction()
        module.callTestFunction()

        warningsShown = self.flushWarnings()
        self.assertEqual(len(warningsShown), 1)
        message = warningsShown[0]['message']
        category = warningsShown[0]['category']
        filename = warningsShown[0]['filename']
        lineno = warningsShown[0]['lineno']
        msg = warnings.formatwarning(message, category, filename, lineno)
        self.assertTrue(
            msg.endswith("module.py:9: DeprecationWarning: A Warning String\n"
                         "  return a\n"),
            "Unexpected warning string: %r" % (msg,))
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_warningToFile(self):
        """
        L{twisted.python.log.showwarning} passes warnings with an explicit file
        target on to the underlying Python warning system.
        """
        message = "another unique message"
        category = FakeWarning
        filename = "warning-filename.py"
        lineno = 31

        output = StringIO()
        log.showwarning(message, category, filename, lineno, file=output)

        self.assertEqual(
            output.getvalue(),
            warnings.formatwarning(message, category, filename, lineno))

        # In Python 2.6 and higher, warnings.showwarning accepts
        # a "line" argument which gives the source line the warning
        # message is to include.
        line = "hello world"
        output = StringIO()
        log.showwarning(message, category, filename, lineno, file=output,
                        line=line)

        self.assertEqual(
            output.getvalue(),
            warnings.formatwarning(message, category, filename, lineno,
                                   line))
项目:scanpy    作者:theislab    | 项目源码 | 文件源码
def warn_with_traceback(message, category, filename, lineno, file=None, line=None):
    """Get full tracebacks when warning is raised by setting

    warnings.showwarning = warn_with_traceback

    See also
    --------
    http://stackoverflow.com/questions/22373927/get-traceback-of-warnings
    """
    import warnings
    import traceback
    traceback.print_stack()
    log = file if hasattr(file, 'write') else sys.stderr
    settings.write(warnings.formatwarning(message, category, filename, lineno, line))
项目:watcher    作者:nosmokingbandit    | 项目源码 | 文件源码
def __call__(self):
        """Run all check_* methods."""
        if self.on:
            oldformatwarning = warnings.formatwarning
            warnings.formatwarning = self.formatwarning
            try:
                for name in dir(self):
                    if name.startswith("check_"):
                        method = getattr(self, name)
                        if method and hasattr(method, '__call__'):
                            method()
            finally:
                warnings.formatwarning = oldformatwarning
项目:watcher    作者:nosmokingbandit    | 项目源码 | 文件源码
def formatwarning(self, message, category, filename, lineno, line=None):
        """Function to format a warning."""
        return "CherryPy Checker:\n%s\n\n" % message

    # This value should be set inside _cpconfig.
项目:maas    作者:maas    | 项目源码 | 文件源码
def show_warning_via_twisted(
        message, category, filename, lineno, file=None, line=None):
    """Replacement for `warnings.showwarning` that logs via Twisted."""
    if file is None:
        # Try to find a module name with which to log this warning.
        module = get_module_for_file(filename)
        logger = twistedModern.Logger(
            "global" if module is None else module.__name__)
        # `message` is/can be an instance of `category`, so stringify.
        logger.warn(
            "{category}: {message}", message=str(message),
            category=category.__qualname__, filename=filename,
            lineno=lineno, line=line)
    else:
        # It's not clear why and when `file` will be specified, but try to
        # honour the intention.
        warning = warnings.formatwarning(
            message, category, filename, lineno, line)
        try:
            file.write(warning)
            file.flush()
        except OSError:
            pass  # We tried.


# Those levels for which we should emit log events.
项目:BreezyCreate2    作者:simondlevy    | 项目源码 | 文件源码
def digit_led_ascii(self, display_string):
        """This command controls the four 7 segment displays using ASCII character codes.

            Arguments:
                display_string: A four character string to be displayed. This must be four
                    characters. Any blank characters should be represented with a space: ' '
                    Due to the limited display, there is no control over upper or lowercase
                    letters. create2api will automatically convert all chars to uppercase, but
                    some letters (Such as 'B' and 'D') will still display as lowercase on the
                    Create 2's display. C'est la vie.
        """
        noError = True
        display_string = display_string.upper()
        if len(display_string) == 4:
            display_list = []
        else:
            #Too many or too few characters!
            noError = False
            raise _ROIDataByteError("Invalid ASCII input (Must be EXACTLY four characters)")
        if noError:
            #Need to map ascii to numbers from the dict.
            for i in range (0,4):
                #Check that the character is in the list, if it is, add it.
                if display_string[i] in self.config.data['ascii table']:
                    display_list.append(self.config.data['ascii table'][display_string[i]])
                else:
                    # Char was not available. Just print a blank space
                    # Raise an error so the software knows that the input was bad
                    display_list.append(self.config.data['ascii table'][' '])
                    warnings.formatwarning = custom_format_warning
                    warnings.warn("Warning: Char '" + display_string[i] + "' was not found in ascii table")

            self.SCI.send(self.config.data['opcodes']['digit_led_ascii'], tuple(display_list))
        else:
            raise _ROIFailedToSendError("Invalid data, failed to send")



    #NOTE ABOUT SONGS: For some reason you cannot play a new song immediately
    #after playing a different one, only the first song will play. You have to
    #time.sleep() at least a fraction of a second for the speaker to process
项目:BreezyCreate2    作者:simondlevy    | 项目源码 | 文件源码
def play_song(self,song_number,note_string):
        """
        Creates and plays a new song based off a string of notes and durations. 
        note_string - a string of notes,durations
        for example: 'G5,16,G3,16,A#4,30'
        """
        #splits the string of notes and durations into two lists
        split_list= note_string.split(',')
        note_list = split_list[0::2]
        duration_list = split_list[1::2]
        #creates a list for serial codes
        play_list = []
        #convert the durations to integers
        duration_list = map(int, duration_list)
        noError = True

        if noError:
            #Need to map midi to numbers from the dict.
            for i in range (0,len(note_list)):
                #Check that the note is in the list, if it is, add it.
                if note_list[i] in self.config.data['midi table']:
                    play_list.append(self.config.data['midi table'][note_list[i]])
                    play_list.append(duration_list[i])
                else:
                    # Note was not available. Play a rest
                    # Raise an error so the software knows that the input was bad
                    play_list.append(self.config.data['midi table']['rest'])
                    play_list.append(duration_list[i])
                    warnings.formatwarning = custom_format_warning
                    warnings.warn("Warning: Note '" + note_string + "' was not found in midi table")

            #play the song
            self.create_song(song_number,play_list)
            self.play(song_number)
        else:
            raise _ROIFailedToSendError("Invalid data, failed to send")
项目:lago    作者:lago-project    | 项目源码 | 文件源码
def main():

    # Trigger cleanup on SIGTERM and SIGHUP
    signal(SIGTERM, exit_handler)
    signal(SIGHUP, exit_handler)

    cli_plugins = lago.plugins.load_plugins(
        lago.plugins.PLUGIN_ENTRY_POINTS['cli']
    )
    out_plugins = lago.plugins.load_plugins(
        lago.plugins.PLUGIN_ENTRY_POINTS['out']
    )
    parser = create_parser(
        cli_plugins=cli_plugins,
        out_plugins=out_plugins,
    )
    args = parser.parse_args()
    config.update_args(args)

    logging.basicConfig(level=logging.DEBUG)
    logging.root.handlers = [
        log_utils.TaskHandler(
            task_tree_depth=args.logdepth,
            level=getattr(logging, args.loglevel.upper()),
            dump_level=logging.ERROR,
            formatter=log_utils.ColorFormatter(fmt='%(msg)s', )
        )
    ]

    logging.captureWarnings(True)
    if args.ignore_warnings:
        logging.getLogger('py.warnings').setLevel(logging.ERROR)
    else:
        warnings.formatwarning = lambda message, *args, **kwargs: message

    args.out_format = out_plugins[args.out_format]
    if args.prefix_path:
        warnings.warn(
            'The option --prefix-path is going to be deprecated, use '
            '--workdir and --prefix instead',
            DeprecationWarning,
        )

    try:
        cli_plugins[args.verb].do_run(args)
    except utils.LagoException as e:
        LOGGER.info(e.message)
        LOGGER.debug(e)
        sys.exit(2)
    except Exception:
        LOGGER.exception('Error occured, aborting')
        sys.exit(1)