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

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+'))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值