0

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.

Seewoo Lee
  • 274
  • 1
  • 3
  • 9
  • 1
    One possibility is to use something like `script(1)` which will capture the screen output as it is displayed. – Noufal Ibrahim Dec 08 '21 at 06:15
  • Make sure you read the man page for `script` if you use it -- it is subject to some significant limitations. – David C. Rankin Dec 09 '21 at 05:24
  • If `tee` output is not printing fast enough, and your command is a python script, you can add the flag `python -u` to unbuffer the output. More info on unbuffered I/O in python: [(python) disable output buffering](https://stackoverflow.com/questions/107705/disable-output-buffering) – dan Dec 11 '21 at 06:54

2 Answers2

0

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.

Seewoo Lee
  • 274
  • 1
  • 3
  • 9
  • 1
    For python scripts you can also use `-u` to disable buffering on python's side: `python3 -u your_program.py | tee output.txt`. – buddemat Dec 09 '21 at 08:24
0

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.

buddemat
  • 4,552
  • 14
  • 29
  • 49