繁体   English   中英

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

[英]Writing terminal output to terminal and to a file?

我有不同的功能,该功能在执行功能时在终端中提供字符串和文本输出。 我使用的命令是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()
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()

使用上下文管理器创建一个写入文件和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()

不要忘记在每次写入后刷新stdout ,因为它已被缓冲。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM