要以编程方式防止出现此类警告,请调整您的代码,以便:
import warnings
if __name__ == '__main__':
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=ImportWarning)
unittest.main()
Source: https://stackoverflow.com/a/40994600/328469 https://stackoverflow.com/a/40994600/328469
Update:
@billjoie 肯定是正确的。如果OP选择使回复52463661 https://stackoverflow.com/a/52463661/328469已接受的答案,我对此表示同意。我可以确认以下内容可以有效地使用 python 版本 2.7.11、3.4.3、3.5.4、3.6.5 和 3.7.1 在运行时抑制此类警告消息:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import warnings
class TestPandasImport(unittest.TestCase):
def setUp(self):
warnings.simplefilter('ignore', category=ImportWarning)
def test_01(self):
import pandas # noqa: E402
self.assertTrue(True)
def test_02(self):
import pandas # noqa: E402
self.assertFalse(False)
if __name__ == '__main__':
unittest.main()
但是,我认为OP应该考虑对单元测试的应用程序代码目标进行更深入的调查,并尝试识别导致实际警告的特定包导入或操作,然后尽可能地抑制警告代码中发生违规的位置。这将避免在整个单元测试类中抑制警告,这可能会无意中掩盖程序其他部分的警告。
在单元测试之外,应用程序代码中的某处:
with warnings.catch_warnings():
warnings.simplefilter('ignore', category=ImportWarning)
# import pandas
# or_ideally_the_application_code_unit_that_imports_pandas()
可能需要做一些工作来隔离代码中导致警告的特定位置或利用导致警告的第三方软件,但开发人员将更清楚地了解警告的原因,这将只提高程序整体的可维护性。