python將print輸出的信息保留到日志文件中
具體代碼如下所示:
import sys import os import sys import io import datetime def create_detail_day(): ''' :return: ''' # 年-月-日 # daytime = datetime.datetime.now().strftime('day'+'%Y-%m-%d') # 年_月_日 daytime = datetime.datetime.now().strftime('day'+'%Y_%m_%d') # 時(shí):分:秒 # hourtime = datetime.datetime.now().strftime("%H:%M:%S") # hourtime = datetime.datetime.now().strftime('time' + "%H_%M_%S") detail_time = daytime # print(daytime + "-" + hourtime) # detail_time = daytime + "__" + hourtime return detail_time def make_print_to_file(path='./'): ''' example: use make_print_to_file() , and the all the information of funtion print , will be write in to a log file :param path: the path to save print information :return: ''' class Logger(object): def __init__(self, filename="Default.log", path="./"): sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') self.terminal = sys.stdout self.log = open(os.path.join(path, filename), "a", encoding='utf8') def write(self, message): self.terminal.write(message) self.log.write(message) def flush(self): pass sys.stdout = Logger(create_detail_day() + '.log', path=path) print(create_detail_time().center(60,'*')) if __name__ == '__main__': make_print_to_file(path="/home/log/") print('explanation'.center(80, '*')) info1 = '從大到小排序' info2 = ' sort the form large to small' print(info1) print(info2) print('END: explanation'.center(80, '*'))
總結(jié)
以上所述是小編給大家介紹的python將print輸出的信息保留到日志文件中,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
Python Sweetviz輕松實(shí)現(xiàn)探索性數(shù)據(jù)分析
Sweetviz是一個(gè)開放源代碼Python庫,可生成精美的高密度可視化文件,以單行代碼啟動(dòng)EDA(探索性數(shù)據(jù)分析)。輸出是一個(gè)完全獨(dú)立的HTML應(yīng)用程序,該系統(tǒng)圍繞快速可視化目標(biāo)值和比較數(shù)據(jù)集而構(gòu)建。其目標(biāo)是幫助快速分析目標(biāo)特征,訓(xùn)練與測試數(shù)據(jù)以及其他此類數(shù)據(jù)表征任務(wù)2021-11-11Python導(dǎo)入Excel表格數(shù)據(jù)并以字典dict格式保存的操作方法
本文介紹基于Python語言,將一個(gè)Excel表格文件中的數(shù)據(jù)導(dǎo)入到Python中,并將其通過字典格式來存儲(chǔ)的方法,感興趣的朋友一起看看吧2023-01-01python強(qiáng)大的hook函數(shù)使用及應(yīng)用場景
鉤子函數(shù)(hook function)是把我們自己實(shí)現(xiàn)的hook函數(shù)在某一時(shí)刻掛接到目標(biāo)掛載點(diǎn)上,這篇文章主要介紹了python強(qiáng)大的hook函數(shù)使用及應(yīng)用場景,需要的朋友可以參考下2023-05-05Python利用memory_profiler實(shí)現(xiàn)內(nèi)存分析
memory_profiler是第三方模塊,用于監(jiān)視進(jìn)程的內(nèi)存消耗以及python程序內(nèi)存消耗的逐行分析。本文將利用memory_profiler實(shí)現(xiàn)內(nèi)存分析,需要的可以參考一下2022-10-10如何在Cloud Studio上執(zhí)行Python代碼?
這篇文章主要介紹了如何在Cloud Studio上執(zhí)行Python代碼?,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08python re正則匹配網(wǎng)頁中圖片url地址的方法
今天小編就為大家分享一篇python re正則匹配網(wǎng)頁中圖片url地址的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12python33 urllib2使用方法細(xì)節(jié)講解
Python 標(biāo)準(zhǔn)庫中有很多實(shí)用的工具類,這里總結(jié)一些 urllib2 的使用細(xì)節(jié):Proxy 的設(shè)置、Timeout 設(shè)置、在 HTTP Request 中加入特定的 、Cookie、使用 HTTP 的 PUT 和 DELETE 方法2013-12-12