Pretty-printing Python interactive output?
Thomas Heller
thomas.heller at ion-tof.com
Wed Sep 8 15:15:19 EDT 1999
>
> 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)
----------------
Thomas Heller
ION-TOF GmbH
More information about the Python-list
mailing list