Color representation of objects in the IPython terminal shell

If I want to have a color representation of objects in a QtConsole or IPython Notebook, I just need to add the _repr_html_ method to the object 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 beautiful color 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 on a cross-platform basis?

Ideally, this will work just like hint patterns:

 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 internal cross-platform IPython layout system in my own console application? I looked into the IPython code base, but I did not find a direct way to use it :(

+4
source share
1 answer

You can use TermColors from IPython.
Minimal example:

 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) 
+2
source

Source: https://habr.com/ru/post/1494552/


All Articles