日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

日志 重定向

發布時間:2025/3/15 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 日志 重定向 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Python 將終端 Terminal 或者控制臺的輸出結果輸出至 log 文件 以文件形式保存
重定義 Logger 類,然后 sys.stdout = Logger(“log文件名及路徑”)

import sysclass Logger(object):def __init__(self, logFile ="Default.log"):self.terminal = sys.stdoutself.log = open(logFile,'a')def write(self,message):self.terminal.write(message)self.log.write(message)def flush(self):passsys.stdout = Logger("log.log")

Python 標準輸出 sys.stdout 重定向
使用 print obj 而非 print(obj)

一些背景
sys.stdout 與 print
當我們在 Python 中打印對象調用 print obj 時候,事實上是調用了 sys.stdout.write(obj+’\n’)

print 將你需要的內容打印到了控制臺,然后追加了一個換行符

print 會調用 sys.stdout 的 write 方法

以下兩行在事實上等價:

sys.stdout.write(‘hello’+’\n’)
print ‘hello’
sys.stdin 與 raw_input
當我們用 raw_input('Input promption: ') 時,事實上是先把提示信息輸出,然后捕獲輸入

以下兩組在事實上等價:

hi=raw_input('hello? ')

print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the ‘\n’ in input stream

從控制臺重定向到文件
原始的 sys.stdout 指向控制臺

如果把文件的對象的引用賦給 sys.stdout,那么 print 調用的就是文件對象的 write 方法

f_handler=open(‘out.log’, ‘w’)
sys.stdout=f_handler
print ‘hello’

this hello can’t be viewed on concole

this hello is in file out.log

記住,如果你還想在控制臺打印一些東西的話,最好先將原始的控制臺對象引用保存下來,向文件中打印之后再恢復 sys.stdout

復制代碼
console=sys.stdout

redirection start

redirection end

sys.stdout=console
復制代碼
同時重定向到控制臺和文件
如果我們希望打印的內容一方面輸出到控制臺,另一方面輸出到文件作為日志保存,那么該怎么辦?

將打印的內容保留在內存中,而不是一打印就將 buffer 釋放刷新,那么放到一個字符串區域中會怎樣?

a=’’
sys.stdout=a
print ‘hello’
OK,上述代碼是無法正常運行的

Traceback (most recent call last):
File “.\hello.py”, line xx, in
print ‘hello’
AttributeError: ‘str’ object has no attribute ‘write’
錯誤很明顯,就是上面強調過的,在嘗試調用 sys.stdout.write() 的時候,發現沒有 write 方法

另外,這里之所以提示 attribute error 而不是找不到函數等等,我猜想是因為 python 將對象/類的函數指針記錄作為對象/類的一個屬性來對待,只是保留了函數的入口地址

既然這樣,那么我們必須給重定向到的對象實現一個 write 方法:

復制代碼
import sys

class redirection:

def __init__(self):self.buff=''self.__console__=sys.stdoutdef write(self, output_stream):self.buff+=output_streamdef to_console(self):sys.stdout=self.__console__print self.buffdef to_file(self, file_path):f=open(file_path,'w')sys.stdout=fprint self.bufff.close()def flush(self):self.buff=''def reset(self):sys.stdout=self.__console__

if name==“main”:
# redirection
r_obj=redirection()
sys.stdout=r_obj

# get output stream print 'hello' print 'there'# redirect to console r_obj.to_console()# redirect to file r_obj.to_file('out.log')# flush buffer r_obj.flush()# reset r_obj.reset()

復制代碼
同樣的,sys.stderr, sys.stdin 也都可以被重定向到多個地址,舉一反三的事情就自己動手實踐吧

總結

以上是生活随笔為你收集整理的日志 重定向的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。