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+'))