Table of contents
scenes to be used
It is necessary to set the output format of the running log of the python script, such as adding a timestamp or other necessary information before each line of output.
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
Read the source code above, the file object of print points to sys.stdout, which is the standard output stream, and prints to the console;
You can directly assign a value to the file object, make it point to the file object, and print out to the file;
print("123", file=open("text1.log", "w"))
text1.log file has been written 123
sys.stdout
sys.stdout is mapped to the console by default, and the printing operation can be redirected to other places by modifying the mapping relationship. For example, the file object reference can be assigned to sys.stdout to realize the redirection of 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")
Revise
The actual call of the print method is the sys.stdout.write method, so the custom object must implement the write method.
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('测试')
reference
(45 messages) python--sys.stdout redirection_Ice American QAQ's Blog-CSDN Blog