zoukankan      html  css  js  c++  java
  • 输出重定向工具

    main主体

    import time
    import sys
    from test.utils import TraceLog


    class Server(object):
    def printLog(self):
    print("start server")
    for i in range(10):
    print(i)
    time.sleep(0.1)
    print("end server ")


    if __name__ == '__main__':
    traceLog = TraceLog("main.log")
    traceLog.start()
    sys.stdout = traceLog
    sys.stderr = traceLog
    server = Server()
    server.printLog()


    # 每当调用print的时候,底层就是在代用sys.stdout.write(str)
    # sys.stdout.write() = traceLog.write()

    utils工具

    '''
    不断记录服务端输入的日志
    实现 >> 和 > 功能
    '''


    import codecs
    from threading import Thread, Lock
    import os

    class TraceLog(Thread):
    def __init__(self, logName):
    # super().__init__() #python3的调用父类的方法,python2用的是super(Class, self).xxx,也是等价于Thread.__init__(self)
    Thread.__init__(self)
    self.logName = logName
    self.lock = Lock()
    self.contexts = []

    def isFile(self):
    if not os.path.exists(self.logName):
    with codecs.open(self.logName, 'w') as f:
    f.write("this log name is: {0} ".format(self.logName))
    f.write("start log ")

    def write(self, context):
    self.contexts.append(context)

    def run(self):
    while 1:
    # self.lock.acquire()
    if len(self.contexts) != 0:
    with codecs.open(self.logName, "a") as f:
    for context in self.contexts:
    f.write(context)
    del self.contexts[:] # 注意不能忘记清空
    # self.lock.release()
  • 相关阅读:
    Centos7上安装docker
    另类SQL拼接方法
    多平台Client TCP通讯组件
    Redis协议详解
    .net下简单快捷的数值高低位切换
    beetle 2.7海量消息广播测试
    FileSync文件同步更新工具
    简单实现TCP下的大文件高效传输
    感知机原理小结
    日志和告警数据挖掘经验谈
  • 原文地址:https://www.cnblogs.com/Jweiqing/p/9095595.html
Copyright © 2011-2022 走看看