同时在控制台和文本文件上打印python

时间:2014-11-07 07:55:24

标签: python file text recursion console

我试图在python控制台上输出注释,同时保存到文本文件中,它应该递归运行。我找到了一个代码并进行了修改:

import sys

def write(input_text):
    print("Coming through stdout")
    # stdout is saved
    save_stdout = sys.stdout

    fh = open(path,"w")
    sys.stdout = fh
    print(input_text)

    # return to normal:
    sys.stdout = save_stdout
    fh.close()
 def testing():
    write('go')

我重复使用此命令,它只保存了最后收到的打印数据。任何线索? 感谢

3 个答案:

答案 0 :(得分:1)

你通过了' w'模式到open功能,删除文件中的任何内容。 你应该使用' a'附加在文件中的模式。

顺便说一句,你应该考虑使用带有两个处理程序的logging模块。一个写入stdout,另一个写入文件。请参阅python文档中的logging handlers

答案 1 :(得分:1)

你需要的只是(假设"路径"已经定义):

def print_twice(*args,**kwargs):
    print(*args,**kwargs)
    with open(path,"a") as f:  # appends to file and closes it when finished
        print(file=f,*args,**kwargs)

完全相同的东西将被打印并写入文件。记录模块对于这个简单的任务来说太过分了。

请告诉我,您实际上并不认为在Python中将数据写入文件需要像在代码中一样使用stdout。那太荒谬了。

答案 2 :(得分:0)

如果您想在屏幕上看到输出并将其保存到文本文件中,那么:

python <your-script-name> | tee output.txt

可以将“ output.txt”更改为所需的任何文件名。如果我误解了您的问题,请忽略。

相关问题