I have a program long_interactive_script.py
which has thousands of print
statements. I want to pipe the program through tee
(or an alternative) so that I can save the output.
If I do
long_interactive_script.py | tee logfile.txt
Python puts its print statements in a 4K buffer, causing me to get:
nothing, nothing, nothing, nothing, a whole lot of text!, nothing,
nothing, a sudo prompt in the middle of a word, nothing, nothing, a
whole lot of text!
In an attempt to avoid the buffer I tried:
unbuffer long_interactive_script.py | tee logfile.txt
But this causes my script to stop being interactive. So when the script breaks into a sudo prompt, it halts.
Note: I cannot simple sudo
BEFORE running the script. The interactive script only requires sudo
on some runs, and I don't want to ask for sudo
when it isn't necessary.
More…
stdbuf -oL long_interactive_script.py | tee -a logfile.txt
works to some extent. I get all the desired data, but I also get this error:
ERROR: ld.so: object '/usr/lib64/coreutils/libstdbuf.so' from LD_PRELOAD cannot be preloaded: ignored.
Best Answer
Specify a zero-sized buffer for Python's standard output stream. You can do this by invoking Python with the
-u
flag, or with the following statement.