【问题标题】:Catch import warnings in Python在 Python 中捕获导入警告
【发布时间】:2015-04-11 00:12:47
【问题描述】:

假设我有一个文件A.py,其中只有以下内容:

导入警告 warnings.warn("A 已弃用", DeprecationWarning)

我想在导入 A 并断言它是 DeprecationWarning 时捕捉到这个警告。目前我正在做以下事情:

导入警告 使用 warnings.catch_warnings(record=True) 作为 w: 进口A

并尝试使用assert_equal(w[0].category, DeprecationWarning) 之类的东西进行断言,但它表明w 是空的。我猜它没有收到警告。有没有其他方法可以做到这一点?

编辑:我忘了补充说我用warnings.simplefilter("always")试过了,但没有记录警告。

编辑 2:它可能与警告级别有关。 [见 cmets]

编辑 3:尝试使用不同的 stacklevels - 0、1、2、3。没有效果:|

【问题讨论】:

  • 如果您使用的是unittest,则有unittest.TestCase.assertWarns()
  • 您的警告级别是多少?我相信DeprecationWarningignored by default。尝试在catch_warnings 之前调用warnings.simplefilter('default')(或调用python -Wd 来运行您的脚本),如here 所记录的那样。查看完整示例 here
  • 对不起,我忘了补充,我用warnings.simplefilter('always')试过了,但没有记录警告,请问EDIT的问题。
  • @CarlGroner,我添加了default 代替always,现在正在记录警告。也会检查 Python 2.7 和 2.6。
  • 如果你能指出一些解释警告级别的东西会很有帮助,因为我是新手。 :)

标签: python


【解决方案1】:

你只需要添加一行

warnings.simplefilter("always")

到你的代码,像这样:

with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    import A

因此,“B.py”的工作版本(实际上)可能如下所示:

import warnings
import unittest

class TestWarnings(unittest.TestCase):

    def test_warnings(self):
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            import A
            self.assertEqual(w[0].category, DeprecationWarning)

if __name__ == '__main__':
    unittest.main()    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2018-05-02
    • 2011-01-07
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多