目录
使用场景
需要设置python脚本的运行日志输出格式,比如说在输出的每一行前添加时间戳或者其他必要的信息。
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对象指向sys.stdout,即标准输出流,打印输出到控制台;
可以直接给file对象赋值,使其指向文件对象,打印输出到文件;
print("123", file=open("text1.log", "w"))
text1.log文件已经写入123
sys.stdout
sys.stdout默认是映射到控制台,可以通过修改映射关系把打印操作重定向到其他地方,例如:可以将文件对象引用赋给sys.stdout,实现sys.stdout的重定向。
# 保存原始sys.stdout进行备份
save_stdout = sys.stdout
# sys.stdout重定向,指向文件对象
sys.stdout = open("test.txt", "w")
# print调用sys.stdout的write方法(此时sys.stdout指向文件对象,实际上调用的就是文件对象的write方法),打印到test.txt文件
print("hello world")
# 恢复,标准输出流
sys.stdout = save_stdout
# print调用sys.stdout的write方法,标准输出流默认打印到控制台
print("hello world again")
修改
print方法调用的实际是sys.stdout.write方法,所以自定义对象一定要实现write方法。
import sys
import datetime
class Print:
def __init__(self):
self.backup_stdout = sys.stdout
self._hidden_end = 0
sys.stdout = self
def __enter__(self,):
return
def close(self):
sys.stdout = self.backup_stdout
return
def write(self,context):
if not self._hidden_end:
header = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
context = f"{header} {context} "
self._hidden_end ^= 1
sys.stdout = self.backup_stdout
sys.stdout.write(context)
self.backup_stdout = sys.stdout
sys.stdout = self
return
def __exit__(self,type, value, trace):
self.close()
return
def func(arg):
print(arg)
return
with Print() as _:
func('测试')