我有一个程序通过打印语句将许多计算和结果输出到控制台.我想编写一些代码来将控制台的所有内容导出(或保存)到一个简单的文本文件中.
I have a program that outputs many calculations and results to the console through the print statement. I want to write some code to export (or save) all the contents of the console to a simple text file.
我搜索了 StackOverflow 和其他网站,但我发现了一些方法可以将打印语句重定向到直接打印到文件,但我希望程序正常工作,将输出显示到控制台,然后在所有操作之后保存其内容程序完成.
I searched StackOverflow and other sites but I found some methods to redirect the print statement to print to a file directly, but I want the program to work normally, to display outputs to the console, then to save its contents AFTER all operations of the program done.
如果重要的话,我将 PyCharm 与 Python2.7 一起使用
I am using PyCharm with Python2.7 if it matters
非常感谢和尊重所有为这个问题做出贡献的人.我终于找到了解决这个问题的方法,只需对我的原始代码进行最少的修改.解决方案由成员@Status 提供,这里是它的链接.
With all thanks and respect to all who contributed to this question. I have finally found a solution to this problem with minimal modifications to my original code. The solution is provided by the member @Status and here is its link .
虽然我在发布我的问题之前进行了很多搜索,但尊敬的成员的回答启发了我进行精确搜索的思路,尤其是执行出色工作的@turkus 和让我大开眼界的@Glostas 的贡献"tee",它引导我找到我发布的解决方案(尽管它不包含tee").
Although I searched a lot before posting my question, but the answers of the respected members enlightened my mind to a precise search especially the contributions of @turkus, who performs an exceptional work, and @Glostas who opened my eyes to the "tee" which guided me to find the solution I posted (although it does not contain "tee").
解决方案,上述帖子略有修改em>:
The solution, as of the mentioned post with slight modifications:
1- 将以下类放入程序中:
1- Put the following Class in the program:
class Logger(object):
"""
Lumberjack class - duplicates sys.stdout to a log file and it's okay
source: https://stackoverflow.com/a/24583265/5820024
"""
def __init__(self, filename="Red.Wood", mode="a", buff=0):
self.stdout = sys.stdout
self.file = open(filename, mode, buff)
sys.stdout = self
def __del__(self):
self.close()
def __enter__(self):
pass
def __exit__(self, *args):
pass
def write(self, message):
self.stdout.write(message)
self.file.write(message)
def flush(self):
self.stdout.flush()
self.file.flush()
os.fsync(self.file.fileno())
def close(self):
if self.stdout != None:
sys.stdout = self.stdout
self.stdout = None
if self.file != None:
self.file.close()
self.file = None
2- 在程序的开头,在任何打印语句之前,放这一行:
2- At the beginning of the program, before any print statements, put this line:
my_console = Logger('my_console_file.txt') # you can change the file's name
3- 在程序的最后,在所有的 print 语句之后,放入这一行:
3- At the end of the program, after all of the print statements, put this line:
my_console.close()
我对此进行了测试,它运行良好,最后我在程序结束后克隆了控制台的输出.
I tested this, and It works perfectly, and finally I have a clone of the console's output after the program ends.
向大家致以最诚挚的问候,并非常感谢所有贡献者.
With best regards to everybody, and Many thanks to all contributors.
这篇关于程序完成后如何将控制台打印到文本文件(Python)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!