Solved: popen4("python -u script.py") redirected to a gui window

André andre.roberge at gmail.com
Sat Jan 28 01:21:24 EST 2006


Sorry about the single-author thread; I have been googling for answers
and trying out for 3 nights... I just want to record to save others the
trouble.

> Earlier this evening, I wrote:
> > Short description: Using a wxPython based app, I would like to take a
> > python script in an editor window, invoke the python interpreter and
> > use another window as stdin/stdout/stderr.
[snip]

I used "exec" instead of popen and solved it.  I had tried originally
with exec but then read that exec could not handle "raw_input", so I
gave up too quickly.

Here are the main parts of the solution.
===============
.    def RunProgram(self, event):
.        user_code = self.GetText()
.        user_code = parser.FixLineEnding(user_code)
.        #redirect stdout/sdterr by redefining them
.        self.parent.log.redirect()
.        myGlobals = globals()
.        myGlobals['raw_input'] = self.myRawInput
.        myGlobals['input'] = self.myInput
.        exec user_code in myGlobals
.        self.parent.log.redirect('reset')

.    def myRawInput(self, text):
.        dlg = wx.TextEntryDialog(self, text,
.                                 'Handling raw_input()', '')
.        if dlg.ShowModal() == wx.ID_OK:
.            user_response = dlg.GetValue() + '\n'
.        dlg.Destroy()
.        return user_response
.
.    def myInput(self, text):
.        dlg = wx.TextEntryDialog(self, text,
.                                 'Handling input()', '')
.        if dlg.ShowModal() == wx.ID_OK:
.            user_response = dlg.GetValue() + '\n'
.        dlg.Destroy()
.        return eval(user_response)
===
.class LogWindow(wx.TextCtrl):
.    def __init__ (self, parent):
.        wx.TextCtrl.__init__(self, parent, -1,
.                             style=wx.TE_MULTILINE|wx.TE_READONLY)
.    def redirect(self, option=''):
.        if option == "reset":
.            sys.stdout = sys.__stdout__
.            sys.stderr = sys.__stderr__
.        else:
.            sys.stdout = self
.            sys.stderr = self




More information about the Python-list mailing list