f=open(
"
myprint.txt
"
,
"
w+
"
)
for
i
in
range(
100
):
print(
"
--{}--
"
.format(i**
2
),file=f,flush=
True)
print(
"
--{}--
"
.format(i **
2
),file=
sys.stdout)
time.sleep(
0.5
)
View Code
将控制台输出的同时即时保存到文件
print函数中的file参数,file=f,输出到文件;file=sys.stdout,输出到终端;flush=True,即时刷新
4.用类实现
import sys
class Logger(object):
def __init__(self, filename='default.log', stream=sys.stdout):
self.terminal = stream
self.log = open(filename, 'a')
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
sys.stdout = Logger(stream=sys.stdout)
# now it works
print('print something')
print("output")
View Code