您的位置:首页 > 编程语言 > Python开发

Python3.6使用logger模块,2次print,重定向,输出信息到指定文件,使用traceback模块重定向错误输出

2018-03-29 01:28 816 查看
import traceback

class Out_file:
def __init__(self):
pass
#logger模块
    def out_to_logging(self):
import logging
logging.basicConfig(filename='out_file.log',level=logging.DEBUG)
logging.debug('this message shoud goto the log file')
logging.info('so shoud this ')
logging.warning('and this , too')
#使用二次print
def out_to_printprint(self):
import os
#first 输出到console
print('filepath:',__file__,'\nfilename:',os.path.basename(__file__))
#第二句输出到txt
with open('outputprint.txt','a+') as f:
print('filepath:',__file__,'\nfilename:',os.path.basename(__file__))
#也可以用f.write("message")的方式写入文件

#利用输出重定向输出两次,同样输出程序path和文件名

def out_3(self):
import os
import sys
temp = sys.stdout#记录当前输出指向,默认是consle
with open('outputlog.txt','a+') as f:
sys.stdout = f #输出指向txt文件
print('filepath:',__file__,'\nfilename:',os.path.basename(__file__))
print('some other')
print('information')
sys.stdout = temp
print(f.readlines())#将记录在文件中的结果输出到屏幕
def plus_2(self):
return 1/0

if __name__ == '__main__' :
try:
o = Out_file()
o.out_3()
o.out_to_logging()
o.out_to_printprint()
print(o.plus_2())
except Exception as e:
#使用traceback模块输出错误信息
         traceback.print_exc(file=open('err.txt','a+'))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐