method one:
import sys
class Logger(object):
def __init__(self, filename='default.log', stream=sys.stdout):
self.terminal = stream
self.log = open(filename, 'a') # add content
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
# now it works
sys.stdout = Logger('a.txt', sys.stdout)
print('print something')
import time
for i in range(10):
now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) # get time
print("now-->", now) # 将会输出到控制台,且同时输出到日志文件中去
time.sleep(1) # 间隔1秒输出
illustrate:
- When the content of a print() line is extremely long (for example: very long JSON format text), the content of the file will not be displayed completely, there is a length limit, and it will automatically disappear at a certain point. That is to say: when using this method, there is a length limit for single-line text.
Specific reference: Safe Development/Python–29–Console content is output to a local file
Method Two:
mylog = open('a.txt', mode='a', encoding='utf-8') # 设置输出的文件及设置
print("now we will start!!!") # 输出到控制台
print("now we will start!!!", file=mylog) # 输出到日志文件中去
import time
for i in range(10):
now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
print("now --> {} \n".format(now), file=mylog)
time.sleep(1)
print(time.time())
mylog.close() # 关闭日志流
Or write like this (all are only output to the log file)
sys.stdout = open('a.txt', mode='a', encoding='utf-8') # 设置输出的文件及设置
print("now we will start!!!") # 输出到日志文件中去
import time
for i in range(10):
now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
print("now --> {} \n".format(now))
time.sleep(1)
print(time.time())
Method 3:
Execute in the terminal, such as:python your_program.py > logger.txt