代码之家  ›  专栏  ›  技术社区  ›  Björn Pollex

如何将脚本输出写入文件和命令行?

  •  7
  • Björn Pollex  · 技术社区  · 14 年前

    我有一个从命令行运行的长时间运行的python脚本。脚本将进度消息和结果写入标准输出。我想捕获脚本在文件中写入标准输出的所有内容,但也可以在命令行中看到。或者,我希望输出立即转到该文件,以便使用 tail 查看进度。我尝试过:

    python MyLongRunngingScript.py | tee log.txt
    

    但它不会生成任何输出(只是运行脚本会按预期生成输出)。有人能提出一个简单的解决方案吗?我使用的是Mac OS X 10.6.4。

    编辑 我正在使用 print 在我的脚本中输出。

    3 回复  |  直到 14 年前
        1
  •  16
  •   Imre L    14 年前

    python -u MyLongRunngingScript.py | tee log.txt
    
        2
  •  2
  •   BatchyX    14 年前

    class OutputSplitter(object):
        def __init__(self, real_output, *open_files):
            self.__stdout = real_output
            self.__fds = open_files
            self.encoding = real_output.encoding
        def write(self, string):
            self.__stdout.write(string) # don't catch exception on that one.
            self.__stdout.flush()
            for fd in self.__fds:
                try:
                    fd.write(string)
                    fd.flush()
                except IOError:
                    pass # do what you want here. 
        def flush(self):
            pass # already flushed
    

    stdout_saved = sys.stdout
    logfile = open("log.txt","a") # check exception on that one.
    sys.stdout = OutputSplitter(stdout_saved, logfile)
    

    print

        3
  •  1
  •   Doug    14 年前

    sys.stdout.flush() tee stdout