5

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.

2
  • Here is the similar question with an answer: paramiko with continuous stdout Commented Apr 26, 2017 at 14:47
  • I read and followed it but no difference Commented Apr 26, 2017 at 14:58

1 Answer 1

6

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()
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing ! It works now ! Thank you so much. You save my night

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.