Embedding a Python shell inside a Python program

2019-03-09 17:15发布

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.

标签: python shell
5条回答
趁早两清
2楼-- · 2019-03-09 17:32

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

查看更多
手持菜刀,她持情操
3楼-- · 2019-03-09 17:34

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

Some examples from effbot.

查看更多
Bombasti
4楼-- · 2019-03-09 17:41

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.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-03-09 17:46

I use pdb.set_trace() as a shell. It also has some debugging capabilities :)

查看更多
叛逆
6楼-- · 2019-03-09 17:52

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

查看更多
登录 后发表回答