将终端输出写入终端和文件?

时间:2016-09-22 02:44:05

标签: python

我有不同的功能,在功能执行期间在终端中输入字符串和文本。我使用的命令是sys.stdout.write

在我正在创建文件并调用上面提到的那些函数的函数之一中。运行此函数时,我需要写入文件中不同函数的所有sys.output.write输出以及终端。

示例代码如下:

def func1():
  sys.stdout.write('A')
  sys.stdout.write('B')

def func2():
  sys.stdout.write('C')
  sys.stdout.write('D')
def main():
  fileName=open("log.txt","W+")
  func1()
  func2()
  --------------------
  # need output ABCD both in terminal and write in logfile as well
  # unfortunately cannot change anything in func1() and func2()

2 个答案:

答案 0 :(得分:1)

import sys
def func1():
  sys.stdout.write('A')
  sys.stdout.write('B')

def func2():
  sys.stdout.write('C')
  sys.stdout.write('D')



class MyCoolOs:
  def __init__(self,stdout,f):
    self.stdout = stdout
    self.f = f

  def write(self,s):
    self.f.write(s)
    self.stdout.write(s)


def main():
  f=open("log.txt","a")
  sys.stdout = MyCoolOs(sys.stdout,f)
  func1()
  func2()

main()

答案 1 :(得分:1)

使用上下文管理器创建一个写入文件的包装器SELECT astrono FROM mytable GROUP BY astrono HAVING bool_or(projectname='Apollo') OR bool_or(projectname='Shuttle');

stdout

请勿忘记在每次写入后刷新class Tee(object): def __init__(self, log_file_name, stdout): self.log_file_name = log_file_name self.stdout = stdout def __enter__(self): self.log_file = open(self.log_file_name, 'a', 0) return self def __exit__(self, exc_type, exc_value, exc_traceback): self.log_file.close() def write(self, data): self.log_file.write(data) self.stdout.write(data) self.stdout.flush() def main(): with Tee('log.txt', sys.stdout) as sys.stdout: func1() func2() ,因为它已被缓冲。