python sys.stderr重定向error信息

sys.stderr

当需要使用python来创建程序出现error的日志该怎么设计呢?鄙人学完python之后,就直接使用django、numpy、sklearn等现成的框架了,所以没开发过类似的error日志,不过,通过想象力,鄙人认为可以使用sys库中的stderr将error重定向到一个称为error日志的文件中。


sys.stderr重定向输出error信息实例代码

import sys
import traceback
f = open('errorlog.txt','a')
sys.stderr = f
try:
    int('abc')
except:
    traceback.print_exc()

f.close()
#在终端输入指令:python3 test.py运行文件,之后在与test.py同一目录下打开errorlog.txt文件,里头的内容为:
Traceback (most recent call last):
  File "test.py", line 6, in <module>
    int('abc')
ValueError: invalid literal for int() with base 10: 'abc'
 

全栈后端 / Python库 :









Copyright © 2022-2024 笨鸟工具 x1y1z1.com All Rights Reserved.