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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With