Python警告消息输出(Python warning message output)
使用此代码:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import warnings
if sys.version_info[0] >= 3:
...
else:
warnings.warn("Python 3.x is required!", RuntimeWarning)
我得到的else输出是:
Warning (from warnings module):
File "C:\Users\..., line 10
warnings.warn("Python 3.x is required!", RuntimeWarning)
RuntimeWarning: Python 3.x is required!
有没有办法摆脱输出的前3行,只显示“RuntimeWarning:Python 3.x是必需的!” ?
With this code:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import warnings
if sys.version_info[0] >= 3:
...
else:
warnings.warn("Python 3.x is required!", RuntimeWarning)
And the else output I get is:
Warning (from warnings module):
File "C:\Users\..., line 10
warnings.warn("Python 3.x is required!", RuntimeWarning)
RuntimeWarning: Python 3.x is required!
Is there any way of getting rid of the first 3 lines of the output and only display "RuntimeWarning: Python 3.x is required!" ?
原文:https://stackoverflow.com/questions/41269618
2020-09-29 11:09
满意答案
警告中的堆栈级别
您会注意到,默认情况下,警告消息包含生成它的源行(如果可用)。 但是,使用实际警告消息查看代码行并不是那么有用。 相反,你可以告诉warn()它必须走多远才能找到被称为包含警告的函数的行。 这样,不推荐使用的函数的用户可以看到调用函数的位置,而不是函数的实现。
# warnings_warn_stacklevel.py
import warnings
def old_function():
warnings.warn(
'old_function() is deprecated, use new_function() instead',
stacklevel=2)
def caller_of_old_function():
old_function()
caller_of_old_function()
请注意,在此示