I want to save the terminal output as a file and also see the output immediately. There are a lot of related questions but the answers are not satisfying. For example,
my_command > output.txt
does not print output to terminal. Another answer, which is
my_command | tee output.txt
prints output to terminal after the process is completed, not immediately. Although I can append each line when I print the output in python code, but this does not seem to be a right way to solve issue.
Update: it seems that tee
flushes output to terminal with certain amount of units.
CodePudding user response:
Here's a solution that only works for python scripts.
Whenever the script prints something on terminal with print
function, instead of
print("some message")
use
print("some message", flush=True)
and with the shell command
$ python3 my_script.py |& tee output.txt
it worked well.
CodePudding user response:
You can use stdfbuf
to modify the buffering behavior of the standard streams of a command. Something like
stdbuf -o0 your_command | stdbuf -i0 -o0 tee
should get rid of the buffering.
Note, this does not work for commands that override the buffering settings of their standard streams, see also this post.