[英]Log terminal output to a text file python
Is there a way to log python print statements to a file有没有办法将 python 打印语句记录到文件中
Method 1 I know about python file.py > data.txt
but this will log the crash error in case the script crashes or the last thing the was displayed and won't log anything while the program is running which in my case it will keep on running until I kill it方法 1我知道
python file.py > data.txt
但这将记录崩溃错误,以防脚本崩溃或显示的最后一件事,并且在程序运行时不会记录任何内容,在我的情况下它将保持一直跑到我杀了它
Method 2 I can use subprocess from another file to check the output but this also doesn't work for me since I am planning on using a single compiled python exe (elf in case of linux ) and not two .py
script or an exe with a .py
方法 2我可以使用另一个文件中的子进程来检查 output 但这对我也不起作用,因为我打算使用单个编译的 python exe (如果是 ZE206A54E97690CCE50CC872 而不是
.py
则为精灵)一个.py
method 3 I tried using script data.txt
but this seems to have the same effect as the first method方法 3我尝试使用
script data.txt
但这似乎与第一种方法具有相同的效果
Note that the goal is to log everything in the terminal before executing the os.system("clear")
line and everything after the previous clear command请注意,目标是在执行
os.system("clear")
行之前记录终端中的所有内容以及上一个 clear 命令之后的所有内容
from time import time
from os import system
def log_terminal():
## log whatever text is displayed in the terminal to a text file in that current moment
pass
while True:
print (f"hello time is {int(time())}")
log_terminal()
os.system("clear")
Can recommend logging
for doing this.可以建议为此进行
logging
。 Simple example:简单的例子:
import logging
logging.basicConfig(filename='output.txt', level=logging.DEBUG, format='')
def we_prints(data):
logging.info(data)
print(data)
we_prints("some data we are logging")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.