I am programming a GUI software has a terminal window (wxCtrl) to display external program's output in real time while it is executing.
I tried subprocess.Popen, this doesn't work as expected because it will hang my GUI while it is running, and only gives the output after the execution finished.
def miExecuteCmd(self, cmd):
self.terminal.addText("\n###\n\n")
self.terminal.addText("Executing: %s\n" % cmd)
args = shlex.split(cmd)
p = subprocess.Popen(args, stdout = subprocess.PIPE)
output = p.stdout.readlines()
output = "".join(output)
self.terminal.addText(output)
if (p.returncode != None and p.returncode != 0 ):
self.terminal.addText("Command Execution Problem, return code is %d\n" % p.returncode)
return output
Now I'm trying to use pexpect, I read this post, how to use pexpect to get spontaneous output of subprocess in python
So I coded something like,
def miExecuteCmd(self, cmd):
self.terminal.addText("\n###\n\n")
self.terminal.addText("Executing: %s\n" % cmd)
output = []
child = pexpect.spawn(cmd)
while True:
try:
child.expect('\n')
line = child.before
output.append(line)
self.terminal.addText(line)
except pexpect.EOF:
break
if child.exitstatus != None and child.exitstatus != 0:
line = "Command Execution Problem, return code is %d\n" % child.exitstatus
self.terminal.addText(line)
output.append(line)
output = "".join(output)
return output
But still the GUI will freeze while I used a long time running cmd.
So I am asking for a simple pexpect solution allowing me to operate my GUI and see the cmd's output at the same time.
I read the pexpect document, it seems pexpect.spawn() should start a separated thread for the command, now I'm confused whether put pexpect.spawn() in a new thread.