1.sys.stdout
stdout用于print和状态表达式的结果输出,及input()的瞬时输出
sys.stdout的形式就是print的一种默认输出格式
import os
sys.stdout.write("hello world" + "\n")
print("hello world")
以上两个输出是相同的
print 默认换行
stdout.write 默认不换行+++++++++
2.sys.stderr
stderr与stdout一样,用于重定向错误信息至某个文件
简而言之就是把输出记录在某个文件当中。
import sys
import traceback
__stderr__ = sys.stderr
sys.stderr = open('errorlog_abc.txt','a')
# 使用traceback 函数定位错误信息
try:
1/0
except:
traceback.print_exc()
3.open
open(path, ‘-模式-‘,encoding=’UTF-8’)
即open(路径+文件名, 读写模式, 编码)
在python对文件进行读写操作的时候,常常涉及到“读写模式”,整理了一下常见的几种模式,如下:
读写模式:
r :只读
r+ : 读写
w : 新建(会对原有文件进行覆盖)
a : 追加
b : 二进制文件
从控制台重定向到文件
stdout 和 print 可以结合使用的案例。
import sys
file = sys.stdout # 存储原始的输出对象
sys.stdout = open('1.txt', 'w') # 重定向所有的写入内容到 1.txt 文件
print('Citizen_Wang') # 写入到 1.txt 文件中
print('Always fall in love with neighbours') # 继续写入到文件中
sys.stdout.close() # 其实就是 open 文件之后的关闭
sys.stdout = file # 将 print 命令的结果返回给控制台
print('输出信息返回在控制台') # 该信息会在控制台也显示
logger.py
import sys
from datetime import datetime
class Logger(object):
def __init__(self, logpath, syspart=sys.stdout):
self.terminal = syspart # 存储原始的输出对象
self.log = open(logpath, "a") # 重定向所有的写入内容到log文件
def write(self, message):
self.terminal.write(message) #sys.stdout.write() 约等于print()
self.log.write(message) #通过write()函数向文件中写入一行
self.log.flush()
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
def log(*args):
print(f'[{datetime.now()}]', *args)