需求 服务器执行程序的时候,打印到终端,并且保存打印的信息。
代码如下
import sys
sys.stdout = open('logfile', 'w')
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f = open('logfile', 'w')
backup = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print("hello world") # this should appear in stdout and in file
f.close()
sys.stdout = backup