1. 前言
為了在Python編程中, 利用控制台信息, 我們需要對控制台輸出進行接管(重定向)。在Python中,控制台輸出的接口是sys.stdout,通過分析print與sys.stdout之間的關系,我們就可以實現控制台輸出重定向了。
2. sys.stdout 與 print
當我們在 Python 中打印對象調用
print(obj)
的時候,事實上是調用了
# 在print(obj)的過程中, 會產生兩次調用
sys.stdout.write(obj)
sys.stdout.write('\n')
所以, 我們只要創造一個替代的對象, 實現write方法, 就可以進行控制台輸出重定向了.
3. 實戰 之 同時重定向到控制台和文件
import sys
class __redirection__(object):
def __init__(self, filepath):
self.filepath = filepath
self.buff = ''
self.__console__ = sys.stdout
sys.stdout = self
def write(self, output_stream):
self.buff += output_stream
self.__console__.write(output_stream)
f = open(self.filepath,'w')
f.write(self.buff)
f.close()
def flush(self):
self.buff = ''
def __del__(self):
sys.stdout = self.__console__
if __name__ == '__main__':
def main():
r_obj=__redirection__(r'd:/temp/test.txt')
print('hello')
print('__redirection__')
main()
