2

I want to run a Python script and save its console output to a file, while still being able to see the output in the console. For example, a "Hello World" script as simple as print('Hello World') would show Hello World in the console and also save this output to a file.

I was previously using pythonscript.py > console_output.txt to shell redirect, I can't see anything in the console with this solution (and for some reason, it no longer saves anything to the specified file, no idea why). This is a solution using Linux shell redirection, but now I would like to write a separate python script to do it.

I don't think I need any special error logging stuff. I'm currently using try: except blocks and just printing the Exception and then using that to find the error.

1
  • Check out the unix scriptcommand. Commented Dec 31, 2021 at 12:55

2 Answers 2

1

You can do you something like this:

def custom_print(message_to_print, log_file='output.txt'):
    print(message_to_print)
    with open(log_file, 'a') as of:
        of.write(message_to_print + '\n')

This way you can use custom_print instead of print to be able to both see the result in the console and have the result appended to a log file.

Sign up to request clarification or add additional context in comments.

3 Comments

Would there be any way to incorporate pprint into this solution?
For anyone else that looks at this, I added a newline character so that last line of this function look like this > of.write('\n' + message_to_print). Otherwise, all the output is on a single line.
Definitely forgot it, thanks, I'm updating my answer! Btw you can use the same logic with pprint, but instead of doing of.write(msg) you can define pp_to_f = pprint.PrettyPrinter(indent=4, stream=of) and then dopp_to_f.pprint(msg). Haven't tested id but it should work :)
1

Try tee command, for example: pythonscript.py | tee console_output.txt

3 Comments

This produces the exact same as result as script.py > output.txt. The output file is created, but nothing gets added to it. Again, not sure why this worked before and now it doesn't.
if you run your pythonscript.py without pipe or redirection, do you see anything on the screen? Can you share a snippet of your code? Can you try python -c "print('Hello World')" | tee console_output.txt? Check if you see Hello World on the console and the file.
Interesting, that works completely fine. And yes, if I just do python app.py I can see the stdout in the terminal. @MatteoMoreschini has got a solution that works for me though, so there no need to investigate further. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.