How to duplicate sys.stdout to a log file?

前端 未结 17 1113
醉酒成梦
醉酒成梦 2020-11-22 06:54

Edit: Since it appears that there\'s either no solution, or I\'m doing something so non-standard that nobody knows - I\'ll revise my question to also ask: What is the best w

17条回答
  •  野性不改
    2020-11-22 07:40

    You can also add stderr as well, based on shx2's answer above using class multifile :

    class Log(object):
    
        def __init__(self, path_log, mode="w", encoding="utf-8"):
            h = open(path_log, mode, encoding=encoding)
            sys.stdout = multifile([ sys.stdout, h ])
            sys.stderr = multifile([ sys.stderr, h ])
    
        def __enter__(self):
            """ Necessary if called by with (or with... as) """
            return self     # only necessary if "as"
    
        def __exit__(self, type, value, tb):
            """ Necessary if call by with """
            pass
    
        def __del__(self):
            if sys is not None:
                # restoring
                sys.stdout = sys.__stdout__
                sys.stderr = sys.__stderr__
    
    log = Log("test.txt")
    print("line 1")
    print("line 2", file=sys.stderr)
    del log
    print("line 3 only on screen")
    

提交回复
热议问题