tags:

views:

896

answers:

4
+3  A: 

The Python eval() function only handles expressions. You may want to consider the exec statement instead, which can run any arbitrary Python code.

Greg Hewgill
+10  A: 

You are looking for code - Interpreter base classes, particularly code.interact().

Some examples from effbot.

Van Gale
Those examples are from Python 1.5...
cool-RR
Well, the link to docs is 2.6 and all you need to do is call code.interact(). For another example, here's a link to the Django shell command that is both current and also works with IronPython: http://code.djangoproject.com/browser/django/trunk/django/core/management/commands/shell.py
Van Gale
..that's just for reference for other people needing to embed interpreter. If you're using wxPython then PyCrust is definitely a better solution.
Van Gale
+1  A: 

FWIW, I believe Enthought has written something like this for use with their Python-based (and NumPy-based) visualization suite. I saw a demo two years ago where they indeed let you manipulate objects directly via the GUI or via the Python interpreter.

Also, to add to the first answer, you might have to subclass code.InteractiveConsole to override self.read() and self.write(), so they interact with the GUI. And you'll also have to redirect sys.stdout and sys.stderr to some writable class that writes to the same console.

Before I begin digesting your answer- Do you happen, by any chance, to be Guido?
cool-RR
+3  A: 

Depending on your GUI framework, it may already has been done:

  • For wxpython, look up "PyCrust" - it's very easy to embed into your app
  • For PyQt, pyqtshell

Here's what I did to embed PyCrust into the application:

import wx.py.crust
...
...
# then call

crustFrame = wx.py.crust.CrustFrame(parent = self)
crustFrame.Show()

The self here refers to my main frame (derived from wx.Frame). This creates a PyCrust window that runs in your application and allows you to inspect everything stored in your main frame (because of the self).

Eli Bendersky
I looked up PyCrust, but I don't understand- Does it create another instance of Python? I need something that will control the same instance of Python that the main program runs in.
cool-RR
Added code sample. It runs in the same instance, and can access (and modify) the the object that is given it as a parent.
Eli Bendersky
Thanks, worked great!
cool-RR