Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store output printed on terminal console to a text file in Python

Tags:

python

I have a large python script. It prints a bunch of output on my terminal console. The problem is the print is not happening altogether. Some print statements print one blob of statements together, then under that some other part of code prints some stuff. It goes on as long as the main loop runs.

Issue is I get the output as I want but all is getting printed on console as that is where we are running the python main script.

It would be very helpful if along with the print happening at console, I can get all the output in console in same format to a text file also for retention.

Again, there are bunch of print statements occurring in different parts of the whole script. So not sure how to retain the whole output of console in same format to a final text file.

like image 670
Baktaawar Avatar asked Jan 29 '26 10:01

Baktaawar


2 Answers

I would rather go ahead with bash and use tee command. It redirects the output to a file too.

python -u my.py | tee my_file.txt

like image 164
bigbounty Avatar answered Jan 31 '26 23:01

bigbounty


If you want to do the redirection within the Python script, setting sys.stdout to a file object does the trick:

import sys
sys.stdout = open('file', 'w')
print('test')

A far more common method is to use shell redirection when executing (same on Windows and Linux):

$ python foo.py > file

Check this thread Redirect stdout to a file in Python?

Custom Print function for both console and file, replace all print with printing in the code.

outputFile = open('outputfile.log', 'w')

def printing(text):
    print(text)
    if outputFile:
        outputFile.write(str(text))
like image 24
Vignesh Avatar answered Jan 31 '26 22:01

Vignesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!