无法将标准输出复制到python中的文件

时间:2018-09-22 18:08:16

标签: python

我正在尝试将控制台中打印的任何内容记录到文件中(它应该同时在控制台和文件中打印)。我正在使用命令,即将输出记录到文件中,但是我面临两个问题:1.不在控制台上打印输出,而是直接打印到文件。 2.如果我正在使用sleep命令,则此命令将无法正常工作。任何人都可以通过python代码来帮助我。 这是我的代码

import  time    
sys.stdout = open("for_posterity.txt", "a")
def main():
    while True:
       fun1()
       fun2()
def fun1():
    time.sleep(1)
    print("inside fun 1")
def fun2():
    time.sleep(1)
    print("inside fun 2")
if __name__ == '__main__':
    main()

2 个答案:

答案 0 :(得分:2)

更改sys.stdout后,您将无法写入控制台。 该代码完全按照您的指示执行。如果我查看for_posterity.txt,它会显示

  

内在乐趣1
  内在乐趣2
  内在乐趣1
  内在乐趣2
  ...

如果您想同时使用这两种功能的日志记录功能,则必须同时进行。

def output(message):
    with open("for_posterity.txt", "a") as logfile:
        print (message)
        logfile.write(message + "\n")

def fun1():
    time.sleep(1)
    output("inside fun 1")

def fun2():
    time.sleep(1)
    output("inside fun 2")

但是,当您变得更高级时,您将需要使用日志记录模块,您可以将其配置为写入所需的任意数量的地方,它可以根据发生的情况来决定。

https://docs.python.org/3/library/logging.html

答案 1 :(得分:0)

更新-添加了file.close(),因为没有它在python 3中不起作用

def print_and_write(content):
    print(content)
    file = open("for_posterity.txt", "a")
    file.write(content)
    file.close()

def main():
    while True:
       print_and_write(fun1())
       print_and_write(fun2())
def fun1():
    return("inside fun 1")
def fun2():
    return("inside fun 2")
if __name__ == '__main__':
    main()