1

如果出现警告,我需要能够在我的代码中引发异常。例如,在比较字符串和字节对象时'b' == b'g',应该引发 BytesWarning。我可以用 -bb 标志(即 running python -bb)捕获它,但希望能够在代码本身内完成它。

我试过使用warnings.filterwarnings('error', category=BytesWarning),但它只捕获由warnings.warn().

如何捕获由不正确代码本身产生的警告?

编辑一个简单的例子:

import warnings
warnings.filterwarnings('error', category=BytesWarning)
warnings.warn('message', BytesWarning)

给我

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
BytesWarning: message

但如果我这样做'b' == b'b'而不是调用warnings.warn(),它只会打印错误。

-bb旗帜:

~$ python -bb
Python 3.6.7 (default, Oct 22 2018, 11:32:17)
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 'b' == b'b'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
BytesWarning: Comparison between bytes and string
4

0 回答 0