Python, logging print statements while having them print to stdout

后端 未结 5 1189
暖寄归人
暖寄归人 2020-12-28 11:33

I have a long python script that uses print statements often, I was wondering if it was possible to add some code that would log all of the print statements into a text file

5条回答
  •  旧时难觅i
    2020-12-28 12:08

    Here is a program that does what you describe:

    #! /usr/bin/python3
    
    class Tee:
        def write(self, *args, **kwargs):
            self.out1.write(*args, **kwargs)
            self.out2.write(*args, **kwargs)
        def __init__(self, out1, out2):
            self.out1 = out1
            self.out2 = out2
    
    import sys
    sys.stdout = Tee(open("/tmp/log.txt", "w"), sys.stdout)
    
    print("hello")
    

提交回复
热议问题