python - 如何使用 : python warnings. warn()?

标签 python warnings

这是我写的代码:

#usr/bin/python3
import warnings

def tt():

    warnings.warn("123")

    return 10

x = tt()

print(x)

它打印:

test.py:5: UserWarning: 123

warnings.warn("123")

10

我希望它只打印:

test.py:5: UserWarning: 123
10

没有 warnings.warn("123")

我该怎么办?

最佳答案

您可以替换用于格式化消息的函数;例如:

def warning_on_one_line(message, category, filename, lineno, file=None, line=None):
        return '%s:%s: %s:%s\n' % (filename, lineno, category.__name__, message)

warnings.formatwarning = warning_on_one_line

Python Module of the week article

关于python - 如何使用 : python warnings. warn()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46844809/

相关文章:

python - 如何使用 keras 将数组 reshape 为 3d

python - 如何更快地计算 nltk plaintextcorpus 中的单词?

ios - Storyboard警告 : First baseline layout attribute before iOS 8. 0

c++ - 为什么我没有收到枚举比较不匹配的警告?

ruby - Textmate 错误重复行 "ruby: warning: -K is specified; it is for 1.8 compatibility and may cause odd behavior"

python - 在 CGI 脚本的主目录中导入 python 模块

python - 在 jupyter 笔记本中创建一个原始 python 文件

python - 有什么方法可以在使用 python panda 时显示特定的单元格值以及标题和列值

python - 我可以在自定义 Tkinter Toplevel() 窗口上获取消息框的图标 ="warning"噪音吗?

ios - UIViewController 可能不响应 showRootPopoverButtonItem