Run a program and log to both screen and file in real time

I've written a very simple python program (in reality my program is a lot more complex):

from time import sleep
for i in range(10):
    print(i)
    sleep(1)

to print the digits 0-9, 1 each second over 10 seconds. I've saved it as TestShell.py

I can run it in powershell using

python .\TestShell.py

which outputs correctly, 1 digit each second. However I'd also like to store the output in a log file. I expected to use the Tee-Object for this

python .\TestShell.py | Tee-Object -FilePath .\fileLog.txt

which takes the log file as one parameter, and implicitly writes to console without a 2nd parameter. However now, no output is printed until the entire program is run. That is, I see nothing for 10 seconds, then the numbers 0-9 all at once.

Is there any way to run a (python) file, outputting to the terminal and a log file in real time?


The problem is that the PowerShell Tee-Object doesn't flush the output stream, but only waits for the source to do that, so you get the output at the end of the operation. This is by design.

Use this syntax instead to write the output line-by-line :

python .\TestShell.py | ForEach-Object { Write-Host $_; $_} | Set-Content .\fileLog.txt

Well one approach can be found here

This is to use the -u switch to change the buffering mode of python itself, giving

python -u .\TestShell.py | Tee-Object -FilePath .\fileLog.txt

But that isn't a solution for all languages