python中的sys.stdout重定向解讀
1.print
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
"""
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass
閱讀上面的源代碼,print的file對(duì)象指向sys.stdout,即標(biāo)準(zhǔn)輸出流,打印輸出到控制臺(tái);
可以直接給file對(duì)象賦值,使其指向文件對(duì)象,打印輸出到文件;
print("123", file=open("text1.log", "w"))text1.log文件已經(jīng)寫入123
2.sys.stdout重定向
sys.stdout是python中的標(biāo)準(zhǔn)輸出流,默認(rèn)是映射到控制臺(tái)的,即將信息打印到控制臺(tái)。
在python中調(diào)用print時(shí),默認(rèn)情況下,實(shí)際上是調(diào)用了sys.stdout.write(obj+"\n")
print("hello")
sys.stdout.write("hello\n")控制臺(tái)輸出
hello
hello
3.sys.stdout重定向到文件對(duì)象
sys.stdout默認(rèn)是映射到控制臺(tái),可以通過(guò)修改映射關(guān)系把打印操作重定向到其他地方,
例如:可以將文件對(duì)象引用賦給sys.stdout,實(shí)現(xiàn)sys.stdout的重定向。
# 保存原始sys.stdout進(jìn)行備份
save_stdout = sys.stdout
# sys.stdout重定向,指向文件對(duì)象
sys.stdout = open("test.txt", "w")
# print調(diào)用sys.stdout的write方法(此時(shí)sys.stdout指向文件對(duì)象,實(shí)際上調(diào)用的就是文件對(duì)象的write方法),打印到test.txt文件
print("hello world")
# 恢復(fù),標(biāo)準(zhǔn)輸出流
sys.stdout = save_stdout
# print調(diào)用sys.stdout的write方法,標(biāo)準(zhǔn)輸出流默認(rèn)打印到控制臺(tái)
print("hello world again")
test.txt文件已經(jīng)寫入hello world
控制臺(tái)輸出
hello world again
上面代碼可以理解為:

4.sys.stdout重定向到自定義對(duì)象
sys.stdout可以重定向到一個(gè)實(shí)現(xiàn)write方法的自定義對(duì)象,從上面的例子中知道,print方法調(diào)用的實(shí)際是sys.stdout.write方法,所以自定義對(duì)象一定要實(shí)現(xiàn)write方法。
import sys
import tkinter
import tkinter.scrolledtext
class RedictStdout:
def __init__(self, scroll_text):
# 保存原始sys.stdout進(jìn)行備份
self.save_stdout = sys.stdout
# sys.stdout重定向,指向該對(duì)象
sys.stdout = self
self.scroll_text = scroll_text
def write(self, message):
# message即sys.stdout接收到的輸出信息
self.scroll_text.insert(tkinter.END, message) # 在多行文本控件最后一行插入message
# self.scroll_text.update() # 更新顯示的文本
self.scroll_text.see(tkinter.END) # 始終顯示最后一行,不加這句,當(dāng)文本溢出控件最后一行時(shí),可能不會(huì)自動(dòng)顯示最后一行
def restore(self):
# 恢復(fù)標(biāo)準(zhǔn)輸出流
sys.stdout = self.save_stdout
def click():
print("hello word")
window = tkinter.Tk()
scroll_text = tkinter.scrolledtext.ScrolledText(window, bg="pink")
scroll_text.pack()
button = tkinter.Button(window, text="點(diǎn)擊", command=click)
button.pack()
# 實(shí)例化對(duì)象
rs = RedictStdout(scroll_text)
# print調(diào)用sys.stdout的write方法,sys.stdout指向rs對(duì)象,實(shí)際上print調(diào)用rs的write方法
# rs的write方法,實(shí)現(xiàn)了scrolltext組件插入sys.stdout收到的message信息,即print要打印的信息
window.mainloop()
# 恢復(fù)標(biāo)準(zhǔn)輸出流
rs.restore()
效果:

上面代碼可以理解為:

5.logging模塊日志輸出
logging的基本用法:
# 設(shè)置日志等級(jí)為DEBUG
logging.basicConfig(level=logging.DEBUG)
logging.error("logging error message")
控制臺(tái)輸出
ERROR:root:logging error message
閱讀logging模塊源代碼,發(fā)現(xiàn)basicConfig默認(rèn)創(chuàng)建一個(gè)StreamHandler,并且其指向標(biāo)準(zhǔn)錯(cuò)誤輸出流,即sys.stderr,默認(rèn)情況下日志輸出到控制臺(tái)。
def basicConfig(**kwargs):
"""
Do basic configuration for the logging system.
This function does nothing if the root logger already has handlers
configured, unless the keyword argument *force* is set to ``True``.
It is a convenience method intended for use by simple scripts
to do one-shot configuration of the logging package.
The default behaviour is to create a StreamHandler which writes to
sys.stderr, set a formatter using the BASIC_FORMAT format string, and
add the handler to the root logger.
A number of optional keyword arguments may be specified, which can alter
the default behaviour.
...
class StreamHandler(Handler):
"""
A handler class which writes logging records, appropriately formatted,
to a stream. Note that this class does not close the stream, as
sys.stdout or sys.stderr may be used.
"""
terminator = '\n'
def __init__(self, stream=None):
"""
Initialize the handler.
If stream is not specified, sys.stderr is used.
"""
Handler.__init__(self)
if stream is None:
stream = sys.stderr
self.stream = stream
所以,在4點(diǎn)中直接使用logging的基本用法,是無(wú)法讓scrolltext顯示logging要打印的日志信息的,因?yàn)椋?點(diǎn)中的代碼只做了對(duì)sys.stdout的重定向,我們應(yīng)該加一步對(duì)sys.stderr的重定向。
import logging
import sys
import tkinter
import tkinter.scrolledtext
class RedictStdout:
def __init__(self, scroll_text):
# 保存原始sys.stdout/sys.stderr進(jìn)行備份
self.save_stdout = sys.stdout
self.save_stderr = sys.stderr
# sys.stdout/sys.stderr重定向,指向該對(duì)象
sys.stdout = self
sys.stderr = self
self.scroll_text = scroll_text
def write(self, message):
# message即sys.stdout/sys.stderr接收到的輸出信息
self.scroll_text.insert(tkinter.END, message) # 在多行文本控件最后一行插入message
# self.scroll_text.update() # 更新顯示的文本
self.scroll_text.see(tkinter.END) # 始終顯示最后一行,不加這句,當(dāng)文本溢出控件最后一行時(shí),可能不會(huì)自動(dòng)顯示最后一行
def restore(self):
# 恢復(fù)標(biāo)準(zhǔn)輸出流
sys.stdout = self.save_stdout
sys.stderr = self.save_stderr
def click():
print("hello word")
logging.error("logging error message")
window = tkinter.Tk()
scroll_text = tkinter.scrolledtext.ScrolledText(window, bg="pink")
scroll_text.pack()
button = tkinter.Button(window, text="點(diǎn)擊", command=click)
button.pack()
# 實(shí)例化對(duì)象
rs = RedictStdout(scroll_text)
# print調(diào)用sys.stdout的write方法,sys.stdout指向rs對(duì)象,實(shí)際上print調(diào)用rs的write方法
# rs的write方法,實(shí)現(xiàn)了scrolltext組件插入sys.stdout收到的message信息,即print要打印的信息
# 設(shè)置日志等級(jí)為DEBUG
logging.basicConfig(level=logging.DEBUG)
# logging.error調(diào)用了sys.stderr的write方法,sys.stderr指向rs對(duì)象,實(shí)際上logging.error調(diào)用rs的write方法
# rs的write方法,實(shí)現(xiàn)了scrolltext組件插入sys.stderr收到的message信息,即logging.error要打印的信息
window.mainloop()
# 恢復(fù)標(biāo)準(zhǔn)輸出流
rs.restore()
效果:

上面代碼可以理解為:

總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
python如何實(shí)現(xiàn)遞歸轉(zhuǎn)非遞歸
這篇文章主要介紹了python如何實(shí)現(xiàn)遞歸轉(zhuǎn)非遞歸,幫助大家更好的理解和學(xué)習(xí)使用python,感興趣的朋友可以了解下2021-02-02
Python實(shí)戰(zhàn)之疫苗研發(fā)情況可視化
2020年底以來(lái),歐美,印度,中國(guó),俄羅斯等多國(guó)得制藥公司紛紛推出了針對(duì)新冠/肺炎的疫苗,這部分主要分析了2020年以來(lái)全球疫情形勢(shì),各類疫苗在全球的地理分布,疫苗在各國(guó)的接種進(jìn)度進(jìn)行可視化展示,需要的朋友可以參考下2021-05-05
tensorflow指定GPU與動(dòng)態(tài)分配GPU memory設(shè)置
今天小編就為大家分享一篇tensorflow指定GPU與動(dòng)態(tài)分配GPU memory設(shè)置,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-02-02

