Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding a Python shell inside a Python program

Tags:

python

shell

I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.)

A mockup that illustrates this: http://cool-rr.com/physicsthing/physicsthing_mockup_thumb.gif

How can I make this sort of thing?

I considered using eval, but I understood that eval can't handle import, for example.

like image 541
Ram Rachum Avatar asked May 01 '09 22:05

Ram Rachum


People also ask

How do I write a Python program in Python shell?

To run the Python Shell, open the command prompt or power shell on Windows and terminal window on mac, write python and press enter. A Python Prompt comprising of three greater-than symbols >>> appears, as shown below. Now, you can enter a single statement and get the result.

Can you code in Python shell?

If you are in the standard Python shell, you can click "File" then choose "New" or simply hit "Ctrl + N" on your keyboard to open a blank script in which you can write your code. You can then press "Ctrl + S" to save it. After writing your code, you can run it by clicking "Run" then "Run Module" or simply press F5.


2 Answers

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

Some examples from effbot.

like image 76
Van Gale Avatar answered Oct 17 '22 04:10

Van Gale


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 (Update 29.04.2011: these days called spyder)

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).

like image 28
Eli Bendersky Avatar answered Oct 17 '22 04:10

Eli Bendersky