An Almost IDE (wxPython)

vegaseat 0 Tallied Votes 805 Views Share

This small code example shows you how to approach the beginning concept of an very simple "IDE" for Python.

''' wx_run_python_code101.py
the beginning of an very simple "IDE" for Python
tested with Python27 and wxPython291 by vegaseat  15jan2013
'''

import wx
import subprocess

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)
        self.SetBackgroundColour("yellow")

        s = "Enter your Python script below:"
        self.label = wx.StaticText(self, wx.ID_ANY, s)
        self.edit = wx.TextCtrl(self, wx.ID_ANY,
            value="",
            size=(300, 180), style=wx.TE_MULTILINE)

        self.result = wx.TextCtrl(self, wx.ID_ANY,
            value="",
            size=(300, 180), style=wx.TE_MULTILINE)

        s = "Run Python27"
        self.button = wx.Button(self, wx.ID_ANY, label=s)
        # bind mouse event to an action
        self.button.Bind(wx.EVT_BUTTON, self.button_click)

        vsizer = wx.BoxSizer(wx.VERTICAL)
        flag1 = wx.LEFT|wx.TOP|wx.RIGHT|wx.EXPAND
        vsizer.Add(self.label, 0, flag=flag1, border=10)
        vsizer.Add(self.edit, 0, flag=flag1, border=10)
        vsizer.Add(self.button, 0, flag=flag1, border=10)
        vsizer.Add(self.result, 0, flag=flag1, border=10)
        self.SetSizer(vsizer)

    def button_click(self, event):
        """run Python button has been clicked"""
        code_str = self.edit.GetValue()
        # save the code
        # uses working directory (improve this!)
        filename = "aaa_mycode.py"
        with open(filename, "w") as fout:
            fout.write(code_str)

        # command to execute Python (use correct path)
        run_python = "C:/Python27/python.exe -u " + filename
        # execute the code and pipe the result to a string
        process = subprocess.Popen(run_python, shell=True,
                                   stdout=subprocess.PIPE)
        # wait till completed
        process.wait()
        # optional check 0 --> success
        #print(process.returncode)
        # read the result to a string
        result_str = process.stdout.read()
        # display the result
        self.result.WriteText(result_str)


app = wx.App(0)
frame = MyFrame(None, 'The Almost IDE', (320, 500))
frame.Show()
app.MainLoop()