美文网首页
算法及Python使用技巧(输出到屏幕变成输出到文件)

算法及Python使用技巧(输出到屏幕变成输出到文件)

作者: 东来_198c | 来源:发表于2018-11-20 03:31 被阅读0次

    在日常使用中可能会遇到这种情况,一个已经写好的print函数

    def printOpt(s, i, j):
        if i == j:
            print("A", i, end='')
        else:
            # print("(", end="")
            print("(", end='')
            printOpt(s, i, s[i][j])
            printOpt(s, s[i][j]+1, j)
            print(")", end='')
    

    然后输出到屏幕了很舒服,但是无法将他改写成字符串。或者很难改成字符串的形式,这样就比较难输出到文件。那么可以用这样的一个函数

    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)
    
        def flush(self):
            pass
    
    

    最后在使用的时候只需要调用logger 再print就可以了。
    注意不要将logger写到循环中,这样会造成多次重复输出。

    相关文章

      网友评论

          本文标题:算法及Python使用技巧(输出到屏幕变成输出到文件)

          本文链接:https://www.haomeiwen.com/subject/hjozfqtx.html