4

If I want to have a colored representation of an objects in a QtConsole or the IPython Notebook, I just have to add the _repr_html_ method to the objects class.

In [1]: class Test(object):
            def __init__(self, x):
                self.x = x

            def _repr_html_(self):
                return '''<span style="color: green">
                       Test{<span style="color: red">%s</span>}
                       </span>''' % self.x
In [2]: Test(33)
Test{33}

This will give me a nice colored representation where Test{ will be green, 33 red and } green again.

Is there a way to do this in the terminal version of the IPython Shell in a cross platform way?

Ideally it would work the same way as the the templates for the prompt customization:

In [1]: class Test(object):
            def __init__(self, x):
                self.x = x

            def _repr_shell_(self):
                return '{color.Green}Test{{color.Red}%s{color.Green}}' % self.x

If not, can I somehow import and use the IPython's internal cross-platform coloring system in my own console application? I looked into the IPython codebase, but I haven't found any direct way to use it :(

Zeugma
  • 31,231
  • 9
  • 69
  • 81
Viktor Kerkez
  • 45,070
  • 12
  • 104
  • 85

1 Answers1

2

You can use the TermColors from IPython.
A minimal example would be:

from IPython.utils.coloransi import TermColors as color
class Test(object):
   def __init__(self, x):
       self.x = x
   def __repr__(self):
       return '{0}Test{{{1}{2}{0}}}'.format(color.Green, color.Red, self.x)
Jakob
  • 19,815
  • 6
  • 75
  • 94
  • Do you know any way I could use the TermColors outside of the IPython environment? On POSIX systems it works fine, but on Windows it just prints out the POSIX escape codes. – Viktor Kerkez Oct 26 '13 at 20:29
  • You can check *colorama*, see these SO questions: http://stackoverflow.com/q/12492810/2870069 and http://stackoverflow.com/q/8358533/2870069 – Jakob Oct 26 '13 at 21:13
  • Yes I know about colorama, but since IPython already does it, I wanted to avoid an extra dependency :) – Viktor Kerkez Oct 26 '13 at 22:04