Q:

View script output over ssh in real time

I am trying to run a local script on a remote machine with ssh.
Let's say this is the python script (printdelay.py) which I am trying to run:
from time import sleep  
print("The first line")  
sleep(10)  
print("The second line")

I execute the script like this:
cat printdelay.py | ssh user@host python

The script executes, but I noticed that I only see the output from the command once the whole script has finished running. I would like to see the output as the script executes, i.e. with a delay between printing the two lines.
I noticed that 
cat printdelay.py | ssh -t -t user@host python 
sort of does what I'm looking for, but then I see a lot of noise in the pseudo terminal, rather than the plain printing of the lines. I guess there is a better way to do this.

A:

Use the -u flag to python:
cat printdelay.py | ssh user@host python -u

The behavior you're seeing is because, when writing to stdout when stdout is not an interactive device such as a tty or pty, the printf family of functions flush the buffer less frequently.  There's not a whole lot you can do about that except give Python a pty, as you discovered.  This will work:
scp printdelay.py user@host:/tmp/timedelay.py
ssh -t user@host python /tmp/timedelay.py

(If you just cat timedelay.py | ssh -tt user@host python, python will have a pty and it will flush the buffer more frequently, but you will have other issues, for instance your script will get printed to stdout due to the way that pty allocation works with ssh.)
You can also try using the coreutils command stdbuf.

