IronPython ConsoleColorMgr

I really liked the ConsoleColorMgr class from my last ipydbg post so I took a few minutes to yank it out into its own seperate module. I also took the opportunity to make a few improvements.

First off, I added support for background colors as well as foreground colors. Furthermore, both colors default to “None” which ConsoleColorMgr takes to mean leave that color unchanged.

from System import Console as _Console

class ConsoleColorMgr(object):
  def __init__(self, foreground = None, background = None):
    self.foreground = foreground
    self.background = background

  def __enter__(self):
    self._tempFG = _Console.ForegroundColor
    self._tempBG = _Console.BackgroundColor  
    if self.foreground: _Console.ForegroundColor = self.foreground
    if self.background: _Console.BackgroundColor = self.background

  def __exit__(self, t, v, tr):
    _Console.ForegroundColor = self._tempFG  
    _Console.BackgroundColor = self._tempBG

The other change I made was to build a set of default ConsoleColorMgr instances in the consolecolor module, one for each of the values in ConsoleColor.

import sys
from System import ConsoleColor, Enum

_curmodule = sys.modules[__name__]

for n in Enum.GetNames(ConsoleColor):
    setattr(_curmodule, n, ConsoleColorMgr(Enum.Parse(ConsoleColor, n)))

Note that for this set of default ConsoleColorMgr instances, I’m only setting the foreground color. If you want to set the background color, you have to create your own ConsoleColorMgr instances. This allows me to write the following:

from __future__ import with_statement
import consolecolor

with consolecolor.Red:
    print "Open the pod bay doors, HAL"
with consolecolor.ConsoleColorMgr(ConsoleColor.Black, ConsoleColor.Red):  
    print "I'm sorry Dave, I'm afraid I can't do that."

If you want it, I’ve put up on my skydrive or it’s available as part of my devhawk_ipy project on GitHub.

Update: Christopher Bermingham pointed out that my sample snippet at the end doesn’t work unless you add from future import with_statement to the top of your python file. I updated my code snippet to include this. Thanks Christopher!


Hello- I am trying to get your consolecolor sample running... What version of IronPython is that? I am running the latest release (which is really 2.0.1 file version 2.0.20209.00). I believe the CPython 2.5 'with' statement doesn't seem to be recognized. >>> with consolecolor.Red: File "", line 1 with consolecolor.Red ^ SyntaxError: unexpected token 'consolecolor'
Me again- I found it in an article that it looks like you have bookmarked :) from __future__ import with_statement Your sample looks great. Thanks!
Woops, thanks for pointing out my mistake Christoper. I've updated the code to include the __future__ import. As for that xmlwriter article, that was the inspiration for this approach!