faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 2 people (50%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

Pretty-printing Python interactive output?

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 238, Thomas Heller


"""
Packages: text
"""
"""
> Is there an easy way or device by which `pprint.pprint' could be called
> automatically on the expression returned by the interactive interpreter?
> Best would be able to easily switch this on and off depending on the
needs.
>
You could play with sys.stdout, but IMHO the following is a better approach:
Run an interpreter loop coded in Python by creating a subclass of 
InteractiveConsole in module code.
The following example writes every line entered into a logfile (not
that you asked for that, but you get the idea):
"""
#----------------
# Interactive Python Interpreter with logfile.
# Usage: Start it, and assign to sys.logfile a file object with
# write() methods.
# Everything you type will be writtem to the logfile.
from code import InteractiveConsole
import sys
sys.logfile = open ("Python.log", "a+")
class LoggingInteractiveInterpreter (InteractiveConsole):
    buffer = []
    def resetbuffer(self):
        """Reset the input buffer, writing all types input to the logfile."""
        if sys.logfile:
            import string
            sys.logfile.write (string.join (self.buffer, "\n"))
            sys.logfile.write ("\n")
        self.buffer = []
banner = "Python %s on %s\n%s" % (sys.version, sys.platform,
sys.copyright)
i = LoggingInteractiveInterpreter()
i.interact (banner)