Output python scripts displayed only on completion when using SSH?

I am running a script to control processes on a remote machine (SSH). Let me call it five .py

#!/usr/bin/python import time, subprocess subprocess.call('echo 0',shell=True) for i in range(1,5): time.sleep(1) print(i) 

If now I run

 ssh user@host five.py 

I would like to see a conclusion

 0 1 2 3 4 

appears on my standard the second second (as if it were running locally). What happens: I immediately get 0 from the echo, and the rest appear immediately after the completion of the entire program. (It doesn't help to insert "five.py" in the bash script; call it "python five.py" or use "print -> sys.stdout, i").

This should be due to the way python writes to stdout, as other programs behave normally. Functional workaround

 import time, subprocess import sys subprocess.call('echo 0',shell=True) for i in range(1,5): time.sleep(1) sys.stdout.write(str(i)+'\n') sys.stdout.flush() 

But there must be a better solution than changing all my print applications!

+4
source share
4 answers

You can add -u to the shebang line as a hint to interjay

 #!/usr/bin/python -u 

You can also reopen stdout with buffering disabled or set line buffering

 import os,sys sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # no buffering sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1) # line buffering 

Normally line buffering is a good choice.

+5
source

A possible solution, found in another topic , suggests using

 ssh -t user@host ./five.py 

which fakes the terminal. Only flaws, ssh printing

 Connection to host closed. 

Moreover.

+2
source

You can replace the sys.stdout object so that it is automatically erased after each entry. This will also affect the print statement. An example taken from this answer :

 class flushfile(object): def __init__(self, f): self.f = f def write(self, x): self.f.write(x) self.f.flush() import sys sys.stdout = flushfile(sys.stdout) 

Edit: Another option is to run Python with the -u option, which will force input and output data to unbuffer.

0
source

One thing you can use, since you are already using Python, Paramiko , it is much nicer to use remote SSH. Below is an article on how I use it in its most basic form.

0
source

Source: https://habr.com/ru/post/1302398/


All Articles