文件读写sys.stdout,sys.stderr和open()函数获得运行状况

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)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值