Hi,
I am trying to write a program that runs a command shell
and shows its output in a wx.TextCtrl.
To monitor the shell output, I am starting a thread
that calls AppendText for every character received.
Almost every time I run this, it crashes - with
various error messages ranging from python runtime
errors to Gtk errors and even segfaults.
Is the wx.TextCtrl not thread-safe?
Is there a better way to do this?
Here is my code:
#!/usr/bin/env python
"""
Run a shell.
"""
__author__ = "Carsten Koch"
__date__ = "2008-10-27"
__version__ = "$Id: run_shell.py $"
__revision__ = "$Revision: 58918 $"
import os
import subprocess
import sys
import threading
import wx
class MainWindow(wx.Frame):
"""
Main window.
"""
def __init__(self):
wx.Frame.__init__(self, None, title=' '.join(sys.argv), size=(800, 600))
panel = wx.Panel(self, -1)
vertical_sizer = wx.BoxSizer(wx.VERTICAL)
self.text_area = wx.TextCtrl(panel, -1, style=wx.TE_MULTILINE)
vertical_sizer.Add(self.text_area, 1, wx.EXPAND)
panel.SetSizer(vertical_sizer)
panel.Layout()
self.Show()
self.shell = subprocess.Popen(os.environ["SHELL"], bufsize=0,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
self.shell_thread = threading.Thread(target=self.read_shell_output)
self.shell_thread.start()
self.last_line_index = 0
self.shell.stdin.write("ls -lR /tmp\n")
def read_shell_output(self):
"""
Read output from shell character by character and display it in text_area.
"""
while True:
output = self.shell.stdout.read(1)
if output == '':
break
self.text_area.AppendText(output)
if __name__ == "__main__":
app = wx.PySimpleApp()
MainWindow()
app.MainLoop()