Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get output of Python remotely in realtime

I have this simple python code:

import time

print "1"
time.sleep(3)
print "2"
time.sleep(2)

And then I use paramiko to run it remotely:

import paramiko

ssh = paramiko.SSHClient()

ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

ssh.connect('X.X.X.X', username='user', key_filename='/home/user/.ssh/id_rsa')

stdin, stdout, stderr = ssh.exec_command('python /home/user/test.py')
print stdout.read()

ssh.close()

It will wait until the Python code finishes and then print everything. But I want it to print each line in real-time. How can I do it?

Thank you.

Update: I tried to run the Python code by ssh command:

ssh [email protected] "python /home/user/test.py"

And the output is the same. It waits until Python code finish and then prints out everything. If I run a shell script remotely, both ssh command and paramiko are fine.

like image 459
thenewasker Avatar asked Apr 26 '17 14:04

thenewasker


1 Answers

Pass -u to python to get unbuffered stdout and iterate over your stdout to get each line:

stdin, stdout, stderr = ssh.exec_command('python -u /home/user/test.py')
for line in stdout:
    print line.rstrip()
like image 93
David Cullen Avatar answered Sep 25 '22 00:09

David Cullen