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


Python warnings.formatwarning函数代码示例

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


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

示例1: _showwarning

    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 logging._warnings_showwarning is not None:
                if PY26:
                    _warnings_showwarning(message, category, filename, lineno,
                                          file, line)
                else:
                    # Python 2.5 and below don't support the line argument
                    _warnings_showwarning(message, category, filename, lineno,
                                          file)
        else:
            if PY26:
                s = warnings.formatwarning(message, category, filename, lineno,
                                           line)
            else:
                s = warnings.formatwarning(message, category, filename, lineno)

            logger = logging.getLogger("py.warnings")
            if not logger.handlers:
                logger.addHandler(NullHandler())
            logger.warning("%s", s)
开发者ID:jhunkeler,项目名称:stsci.tools,代码行数:31,代码来源:logutil.py

示例2: test_warningToFile

    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))
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:29,代码来源:test_log.py

示例3: test_warningToFile

    def test_warningToFile(self):
        """
        L{twisted.python.log.showwarning} passes warnings with an explicit file
        target on to the underlying Python warning system.
        """
        # log.showwarning depends on _oldshowwarning being set, which only
        # happens in startLogging(), which doesn't happen if you're not
        # running under trial. So this test only passes by accident of runner
        # environment.
        if log._oldshowwarning is None:
            raise unittest.SkipTest("Currently this test only runs under trial.")
        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, warnings.showwarning accepts a "line" argument which
        # gives the source line the warning message is to include.
        if sys.version_info >= (2, 6):
            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))
开发者ID:0004c,项目名称:VTK,代码行数:35,代码来源:test_log.py

示例4: showwarning

def showwarning(message, category, filename, lineno, file=None):
    """Hook to write a warning to a file; replace if you like."""
    if file is None:
        file = sys.stderr
    try:
      file.write(warnings.formatwarning(message, category, filename, lineno))
    except:
      file = open ('warnings.log', 'a')
      file.write(warnings.formatwarning(message, category, filename, lineno))
      file.close()
开发者ID:satyadevi-nyros,项目名称:eracks,代码行数:10,代码来源:renderer.py

示例5: customwarn

def customwarn(message, category, filename, lineno, *args, **kwargs):
    """Use the nc2map.warning logger for categories being out of
    Nc2MapWarning and Nc2MapCritical and the default warnings.showwarning
    function for all the others."""
    if category is Nc2MapWarning:
        logger.warning(warnings.formatwarning(
            "\n%s" % message, category, filename, lineno))
    elif category is Nc2MapCritical:
        logger.critical(warnings.formatwarning(
            "\n%s" % message, category, filename, lineno))
    else:
        old_showwarning(message, category, filename, lineno, *args, **kwargs)
开发者ID:Chilipp,项目名称:nc2map,代码行数:12,代码来源:warning.py

示例6: customwarn

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)
开发者ID:Chilipp,项目名称:psyplot,代码行数:13,代码来源:warning.py

示例7: warning_record_to_str

def warning_record_to_str(warning_message):
    """Convert a warnings.WarningMessage to a string, taking in account a lot of unicode shenaningans in Python 2.

    When Python 2 support is dropped this function can be greatly simplified.
    """
    warn_msg = warning_message.message
    unicode_warning = False
    if compat._PY2 and any(isinstance(m, compat.UNICODE_TYPES) for m in warn_msg.args):
        new_args = []
        for m in warn_msg.args:
            new_args.append(
                compat.ascii_escaped(m) if isinstance(m, compat.UNICODE_TYPES) else m
            )
        unicode_warning = list(warn_msg.args) != new_args
        warn_msg.args = new_args

    msg = warnings.formatwarning(
        warn_msg,
        warning_message.category,
        warning_message.filename,
        warning_message.lineno,
        warning_message.line,
    )
    if unicode_warning:
        warnings.warn(
            "Warning is using unicode non convertible to ascii, "
            "converting to a safe representation:\n  {!r}".format(compat.safe_str(msg)),
            UnicodeWarning,
        )
    return msg
开发者ID:mathieu-vallais,项目名称:Docker,代码行数:30,代码来源:warnings.py

示例8: ShowWarning

 def ShowWarning(self, message, category, filename, lineno, file = None):
     import logmodule
     string = warnings.formatwarning(message, category, filename, lineno)
     logmodule.LogTraceback(extraText=string, severity=logmodule.LGWARN, nthParent=3)
     if not file:
         file = sys.stderr
     print >> file, string
开发者ID:connoryang,项目名称:dec-eve-serenity,代码行数:7,代码来源:inifile.py

示例9: warn_with_traceback

		def warn_with_traceback(message, category, filename, lineno, line=None):
			print(u'***startwarning***')
			traceback.print_stack()
			print
			print(warnings.formatwarning(message, category, filename, lineno,
				line))
			print(u'***endwarning***')
开发者ID:dev-jam,项目名称:OpenSesame,代码行数:7,代码来源:qtopensesame.py

示例10: test_filteredOnceWarning

    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,))
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:29,代码来源:test_deprecate.py

示例11: idle_showwarning

 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, file=file, line=line))
     except IOError:
         pass  ## file (probably __stderr__) is invalid, warning dropped.
开发者ID:jingyi2811,项目名称:station-software,代码行数:7,代码来源:PyShell.py

示例12: _showwarning

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)
开发者ID:neofang7,项目名称:ostro-os,代码行数:7,代码来源:main.py

示例13: _showwarning

def _showwarning(message, category, filename, lineno, file=None, line=None):
    """
    Redirect warnings into logging.
    """

    fmtmsg = warnings.formatwarning(message, category, filename, lineno, line)
    LOG.warning(fmtmsg)
开发者ID:xinnet-iaas-openstack,项目名称:io,代码行数:7,代码来源:utils.py

示例14: warn_to_stdout

def warn_to_stdout(message, category, filename, lineno, file=None, line=None):
    """A function to replace warnings.showwarning so that warnings are
         printed to STDOUT instead of STDERR.

         Usage: warnings.showwarning = warn_to_stdout
    """
    sys.stdout.write(warnings.formatwarning(message,category,filename,lineno))
开发者ID:pscholz,项目名称:Ratings2.0,代码行数:7,代码来源:rate_pfds.py

示例15: custom_show_warning

def custom_show_warning(message, category, filename, lineno, file=None, line=None):
        """ 
        Override warnings.showwarning to raise an exception if GTK cannot open the DISPLAY.
        open the display.
        """
        sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))
        if "could not open display" in message:
            raise RuntimeError("Error: Could not open display. Spinic needs a $DISPLAY.")
开发者ID:aalex,项目名称:ubuntu-spinic,代码行数:8,代码来源:runner.py


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