3

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.

5

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.

  • 3
    Or with a suitable version python -u to unbuffer everything or use sys.stdout.flush calls as appropriate or print(flush=True) and of course the usual debate over which is the most pythonic of these multiple ways to do things. – thrig Nov 22 '16 at 19:11
  • Thanks for the explanation. Perhaps you could move the mention of the '-u' flag to the top of the answer. It looks like the neatest solution to me. – SauceCode Nov 22 '16 at 19:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.