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

Python warnings.formatwarning函数代码示例

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

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



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


示例16: customwarn

def customwarn(message, category, filename, lineno, file=None, line=None):
        """
        Override warnings.showwarning to avoid importing gtk when it fails to
        open the display.
        """
        sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))
        if "could not open display" in message:
            raise ImportError("Could not open display")
开发者ID:alg-a,项目名称:scenic,代码行数:8,代码来源:test_vumeter.py


示例17: showwarning

 def showwarning(self, message, category, filename, lineno, file=None, line=None):
     """
     Called when a warning is generated.
     The default behaviour is to write it on stderr, which would lead to it
     being shown as an error.
     """
     warn = warnings.formatwarning(message, category, filename, lineno, line)
     logging.warning(warn)
开发者ID:delmic,项目名称:odemis,代码行数:8,代码来源:main.py


示例18: log_warnings

def log_warnings(message, category, filename, lineno, file=None, line=None):
    WARNLOG = logging.getLogger("Python")
    logging.debug("message=%s message=%r category=%r", message, message, category)
    warning_string = warnings.formatwarning(message,
                                            category,
                                            filename,
                                            lineno)
    WARNLOG.debug("%s", warning_string)
开发者ID:CashStar,项目名称:holland,代码行数:8,代码来源:bootstrap.py


示例19: showWarning

def showWarning(message, category, filename, lineno, file=None, line=None):
  stk = ""
  for s in traceback.format_stack()[:-2]:
    stk += s.decode('utf-8', 'replace')
  QgsMessageLog.logMessage(
    "warning:%s\ntraceback:%s" % ( warnings.formatwarning(message, category, filename, lineno), stk),
    QCoreApplication.translate( "Python", "Python warning" )
  )
开发者ID:ACorradini,项目名称:QGIS,代码行数:8,代码来源:utils.py


示例20: _warning

def _warning(
    message,
    category = galpyWarning,
    filename = '',
    lineno = -1):
    if issubclass(category,galpyWarning):
        print("galpyWarning: "+str(message))
    else:
        print(warnings.formatwarning(message,category,filename,lineno))
开发者ID:astrofrog,项目名称:galpy,代码行数:9,代码来源:__init__.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python warnings.resetwarnings函数代码示例发布时间:2022-05-26
下一篇:
Python warnings.filterwarnings函数代码示例发布时间: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