I'm trying to launch an 'rsync' using subprocess module and Popen inside of a thread. After I call the rsync I need to read the output as well. I'm using the communicate method to read the output. The code runs fine when I do not use a thread. It appears that when I use a thread it hangs on the communicate call. Another thing I've noticed is that when I set shell=False I get nothing back from the communicate when running in a thread.
+4
A:
You didn't supply any code for us to look at, but here's a sample that does something similar to what you describe:
import threading
import subprocess
class MyClass(threading.Thread):
def __init__(self):
self.stdout = None
self.stderr = None
threading.Thread.__init__(self)
def run(self):
p = subprocess.Popen('rsync -av /etc/passwd /tmp'.split(),
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
self.stdout, self.stderr = p.communicate()
myclass = MyClass()
myclass.start()
myclass.join()
print myclass.stdout
Ryan Bright
2009-06-12 04:39:35
Yes that is pretty much exactly what I am doing. I'd like to be read the output inside the thread though. I should also note I'm using Python 2.3. I've grabbed a copy of subprocess from 2.4.
noahd
2009-06-12 04:55:46
then please mark this as "answered"
wr
2009-06-12 12:11:17
I should be more clear that is what I am doing but it doesn't work. In this case the communicate call will not return anything and the command does not appear to execute. If I set shell=True the communicate hangs the thread. Then after I stop the python I end up with a defunct ssh process.
noahd
2009-06-12 12:49:00
I tested the sample code provided and I get the same behavior.I tried substituting a different command like 'ls -la' and I had no issues so I think it has something to do with rsync or maybe this version of python.
noahd
2009-06-12 18:20:57
Got this to work. There was something wrong with my environment. Thanks for your help!
noahd
2009-06-12 18:44:43