本篇内容主要讲解“python异常输出怎么优化”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“python异常输出怎么优化”吧!
一行代码优化输出的异常信息
pip install pretty-errors
写一个函数测试:
def divided_zero():
for i in range(10, -1, -1):
print(10/i)
divided_zero()
在没有import这个pretty-errors
前,输出的错误信息有些冗余:
Traceback (most recent call last):
File "c:\Users\HUAWEI\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "c:\Users\HUAWEI\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py",
line 432, in main
run()
File "c:\Users\HUAWEI\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py",
line 316, in run_file
runpy.run_path(target, run_name='__main__')
File "D:\anaconda3\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "D:\anaconda3\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "D:\anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "d:\source\sorting-visualizer-master\sorting\debug_test.py", line 6, in <module>
divided_zero()
File "d:\source\sorting-visualizer-master\sorting\debug_test.py", line 3, in divided_zero
print(10/i)
ZeroDivisionError: division by zero
我们使用刚安装的pretty_errors
,import
下:
import pretty_errors
def divided_zero():
for i in range(10, -1, -1):
print(10/i)
divided_zero()
此时看看输出的错误信息,非常精简只有2行,去那些冗余信息:
ZeroDivisionError:
division by zero
完整的输出信息如下图片所示,中间一道分割线,然后输出异常的堆栈,最后是精简的异常名称和提示。
到此,相信大家对“python异常输出怎么优化”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。