How to duplicate sys.stdout to a log file?

前端 未结 17 1262
醉酒成梦
醉酒成梦 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:37

    Here is another solution, which is more general than the others -- it supports splitting output (written to sys.stdout) to any number of file-like objects. There's no requirement that __stdout__ itself is included.

    import sys
    
    class multifile(object):
        def __init__(self, files):
            self._files = files
        def __getattr__(self, attr, *args):
            return self._wrap(attr, *args)
        def _wrap(self, attr, *args):
            def g(*a, **kw):
                for f in self._files:
                    res = getattr(f, attr, *args)(*a, **kw)
                return res
            return g
    
    # for a tee-like behavior, use like this:
    sys.stdout = multifile([ sys.stdout, open('myfile.txt', 'w') ])
    
    # all these forms work:
    print 'abc'
    print >>sys.stdout, 'line2'
    sys.stdout.write('line3\n')
    

    NOTE: This is a proof-of-concept. The implementation here is not complete, as it only wraps methods of the file-like objects (e.g. write), leaving out members/properties/setattr, etc. However, it is probably good enough for most people as it currently stands.

    What I like about it, other than its generality, is that it is clean in the sense it doesn't make any direct calls to write, flush, os.dup2, etc.

提交回复
热议问题