views:

586

answers:

2

I am trying to get all output from child process in real time. I use spawn for creating child process but I am confused what I should send for pattern parameter in expect function. Actually I don't understand why it's not an optional parameter. I don't know if I should use send(), child doesn't need input. I'm just trying to write output to GUI. Anyway here's the code

pro=pexpect.spawn('python tx.py')
        while True:
            self.textEdit(pro.expect(['\n'])

edit: I managed to get some output

    self.pro=pexpect.spawn('python tx.py',logfile=file('mylog.txt','w'))
    self.pro.logfile_read = sys.stdout
    while(self.pro.isalive()):      
        try:
            self.textEdit.append(self.pro.read_nonblocking(size=100))
        except pexpect.TIMEOUT:
            self.pro.close(True)
        except pexpect.EOF:
            break
        time.sleep(1)           

I don't still get it. If I use read_nonblocking it still blocks main process, if I don't use it , logfile doesn't get updated so I have no output. Any idea what's wrong here?

A: 

If your spawned program does not need any input, then you do not need pexpect. You need the subprocess module to execute a shell process.

Read here http://docs.python.org/library/subprocess.html

M0E-lnx
I tried it but it also blocks my GUI. I can't see anything going on till that subprocess does his job.
Ufuk Hacıoğulları
You need to use subprocess + threading to keep the gui from freezing.
M0E-lnx
Can you explain it a litte?
Ufuk Hacıoğulları
+1  A: 

I'll give you an example

import subprocess
import threading



def run_in_background():
   mycmd = 'ls -R /home'
   proc = subprocess.Popen(mycnd.split(), stdout=subprocess.Pipe, stderr=subprocess.STDOUT)

def run_thread():
thread = threading.Thread(target=run_in_background, args=())
thread.start()

if __name__=='__main__':
   run_in_background()

I have not tested this code, but basically this is how its done You want threading to keep your GUI from freezing, and you want subprocess to run the shell process.

M0E-lnx
Where do I get the output? If I proc.communicate() in run_in_backgroung() it freezes GUI again. I don't know how to reach PIPE from threading.Thread
Ufuk Hacıoğulları
I just did this myself... Here is the answerhttp://stackoverflow.com/questions/1929018/python-gui-glade-to-display-output-of-shell-process
M0E-lnx