Redirect stdout to a file in Python?

后端 未结 10 1374
轻奢々
轻奢々 2020-11-21 05:26

How do I redirect stdout to an arbitrary file in Python?

When a long-running Python script (e.g, web application) is started from within the ssh session and backgoun

10条回答
  •  情话喂你
    2020-11-21 05:41

    you can try this too much better

    import sys
    
    class Logger(object):
        def __init__(self, filename="Default.log"):
            self.terminal = sys.stdout
            self.log = open(filename, "a")
    
        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)
    
    sys.stdout = Logger("yourlogfilename.txt")
    print "Hello world !" # this is should be saved in yourlogfilename.txt
    

提交回复
热议问题