How to output to the console and file?

前端 未结 8 1211
青春惊慌失措
青春惊慌失措 2020-11-30 02:54

I\'m trying to find out a way in python to redirect the script execution log to a file as well as stdout in a pythonic way. Is there any easy way of achieving t

8条回答
  •  广开言路
    2020-11-30 03:30

    I came up with this [untested]

    import sys
    
    class Tee(object):
        def __init__(self, *files):
            self.files = files
        def write(self, obj):
            for f in self.files:
                f.write(obj)
                f.flush() # If you want the output to be visible immediately
        def flush(self) :
            for f in self.files:
                f.flush()
    
    f = open('out.txt', 'w')
    original = sys.stdout
    sys.stdout = Tee(sys.stdout, f)
    print "test"  # This will go to stdout and the file out.txt
    
    #use the original
    sys.stdout = original
    print "This won't appear on file"  # Only on stdout
    f.close()
    

    print>>xyz in python will expect a write() function in xyz. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz.

提交回复
热议问题