Welcome, guest | Sign In | My Account | Store | Cart

The code module provides the ability to write your own Python shell, which you can use to filter out input or output, and embed it in another application. This recipe shows how this module can be used.

Python, 36 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class FileCacher:
    "Cache the stdout text so we can analyze it before returning it"
    def __init__(self): self.reset()
    def reset(self): self.out = []
    def write(self,line): self.out.append(line)
    def flush(self):
        output = '\n'.join(self.out)
        self.reset()
        return output

class Shell(InteractiveConsole):
    "Wrapper around Python that can filter input/output to the shell"
    def __init__(self):
        self.stdout = sys.stdout
        self.cache = FileCacher()
        InteractiveConsole.__init__(self)
        return

    def get_output(self): sys.stdout = self.cache
    def return_output(self): sys.stdout = self.stdout

    def push(self,line):
        self.get_output()
        # you can filter input here by doing something like
        # line = filter(line)
        InteractiveConsole.push(self,line)
        self.return_output()
        output = self.cache.flush()
        # you can filter the output here by doing something like
        # output = filter(output)
        print output # or do something else with it
        return 

if __name__ == '__main__':
     sh = Shell()
     sh.interact()

The classes in the code module, InteractiveInterpreter and InteractiveConsole, allow you to write your own Python shell, which can be embedded in your user interface and can allow you to specify custom behavior, if desired. I didn't find much documentation on actually using these functions, but luckily got some help from Fernando Perez, of IPython fame. I thought I would submit this recipe here in case other people find it useful.

This recipe uses InteractiveConsole to create your own Python shell. You can use the commented lines in the push() function to filter the input or the output, if, for example, you want to send the graphical output from the shell to another window.

2 comments

Hans Raaf 19 years, 3 months ago  # | flag

It's missing the import statements. To make it work it needs:

import sys
from code import InteractiveConsole
Karl Waedt 18 years, 2 months ago  # | flag

Return code of InteractiveConsole.push(). The return code of InteractiveConsole.push() should be returned by Shell.push(). Otherwise sys.ps2 is not displayed.

Created by Rick Muller on Thu, 2 Dec 2004 (PSF)
Python recipes (4591)
Rick Muller's recipes (10)

Required Modules

  • (none specified)

Other Information and Tasks