Home > Net >  Log terminal output to a text file python
Log terminal output to a text file python

Time:12-13

Is there a way to log python print statements to a file

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

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

method 3 I tried using script data.txt but this seems to have the same effect as the first method

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


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")

CodePudding user response:

Can recommend logging for doing this. 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")
  • Related