thenewasker
thenewasker

Reputation: 135

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.

Upvotes: 5

Views: 5380

Answers (1)

user3657941
user3657941

Reputation:

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()

Upvotes: 6

Related Questions