interactive python shell

brueckd at tbye.com brueckd at tbye.com
Wed Mar 27 14:57:09 EST 2002


On Wed, 27 Mar 2002, ian reinhart geiser wrote:

> 	I have an python application and I would like to provide a
> "console" in the application where users can have an interactive
> session with python that has all of the applications enviroment.
> This is for debugging the system in real time.
>
> 	Is there an easy way to do this?  All it needs to do is execute
> commands and return data.  I am using PyQt for my GUI, so it would be
> cool to fit into there, but I can get away with a input line and a
> display view if that is easier.  This is not for production, only to
> make a more useful debug tool.

It's not too hard, but it does require experience using some other
modules:

Use the 'code' module. More specifically, subclass code.InteractiveConsole
and override the raw_input method so that it gets input from a socket you
pass to the constructor, and override the write method to write the data
back out the socket.

Next, use SocketServer.TCPSocketServer to listen for incoming connections
and create a ConsoleRequestHandler class whose handle method creates a new
console object and calls its interact method. It's helpful to trap
sys.stdout like this:

def handle(self):
  c = YourNewConsoleClass()
  stdout = sys.stdout
  sys.stdout = self.wfile
  try: c.interact()
  finally: sys.stdout = stdout

(if you need stdout to keep going to the main console while you're
debugging then use a custom file-like class that writes to wfile and the
original stdout and install it instead.)

Some extra things to think about:
- your raw_input method in the Console class needs to be interruptible if
your application needs to be able to shutdown and kill the debugging
console, so it might be good to use select to read input in a loop that is
also checking some shutdown flag
- you won't be able to see the local scope of running functions, so for
this console to be useful you'll probably need to have a global variable
or two that reference whatever objects will be most useful during
debugging.
- your server that listens for incoming console connections should listen
only on 127.0.0.1, and it wouldn't hurt to make it password protected.
- make your raw_input function read data 1 character at a time if
possible, so that you can check for chr(4) (Ctrl-D to exit), '\n'
(newlines, to return the line of input), and '\r' (from Windows users,
ignore these).

If you have more questions I'll see if I can post some code..

-Dave





More information about the Python-list mailing list