LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   ssh changes the way python script behaves (https://www.linuxquestions.org/questions/programming-9/ssh-changes-the-way-python-script-behaves-383105/)

shanenin 11-14-2005 02:19 PM

ssh changes the way python script behaves
 
I wrote a python script that checks for new media on my windows box, if it is new it copys it over to my standalone freevo jukebox. Below is a small part of the script that does the actually copying
Code:

source = "/mnt/samba/%s" %i
destination = "/mnt/media/movies"
print "copying %s to %s" %(i, destination)
shutil.copy2(source, destination)

when I ssh into the freevo box then run the script it behaves like I think it shoud. first it runs the print function, then runs the shutil.copy2 function.

here is where it is behaving buggy. if I run the script directly using a command like this
Code:

ssh root@192.168.1.103 /usr/local/bin/sambacopy.py
it does not print to the screen until after it has finished copying. I have found a solution of using sys.stdout.flush() directly after the print statment
Code:

source = "/mnt/samba/%s" %i
destination = "/mnt/media/movies"
print "copying %s to %s" %(i, destination)
sys.stdout.flush()
shutil.copy2(source, destination)

why is the flush function needed when I run the script directly, but not if I ssh into a shell , then run the script

bulliver 11-15-2005 09:08 PM

I think the reason may be that in your second case, ssh is running the command as a subprocess, rather than through a shell. The upshot is that the output is buffered until the command completes.

Your call to "sys.stdout.flush()" flushes the buffer, so the output is printed immediately.

A quick test to see if my guess is correct would be to put this script on your server:
Code:

#!/usr/bin/python
import time
time.sleep(5)
print "some text"
time.sleep(5)
print "some text"

Now run it through ssh. Does it wait 10 seconds and print both messages?

shanenin 11-15-2005 09:10 PM

sounds reasonable :-)

shanenin 11-16-2005 02:19 PM

the script tested as you thought. it waits 10 seconds then prints both to screen. I still do not understand why running the command as a subprocess would cause all of the output not to be flushed until the script finishes.

bulliver 11-16-2005 03:22 PM

Quote:

I still do not understand why running the command as a subprocess would cause all of the output not to be flushed until the script finishes
I don't think there is any actual technical reason for it, it's just the way the OpenSSH developers wrote it...

Again, I'm really just guessing here though ;)


All times are GMT -5. The time now is 06:21 PM.