Fork me on BitBucket

Syntax highlighting and self replicating machines

So the other day I went to the Auckland Makers-Space. There they had a 3d printer printing out replacement parts for itself. The guy told me that in fact all the parts of his 3d printer had been created by his friends 3d printer. Talk about exponential growth of 3d printers. (Check out ponoko to access one)

Anyway I decided to write a how-to article on how I style my python code snippets. firstly easy_install Pygments, then:

from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter

code = open(__file__).read()
print highlight(code, PythonLexer(), HtmlFormatter())
#print HtmlFormatter().get_style_defs('.highlight')

The above code snippet, through the use of __file__, prints the following html source which in turn produces the above code snippet:

<div class="highlight"><pre><span class="kn">from</span> <span class="nn">pygments</span> <span class="kn">import</span> <span class="n">highlight</span> <span class="kn">from</span> <span class="nn">pygments.lexers</span> <span class="kn">import</span> <span class="n">PythonLexer</span> <span class="kn">from</span> <span class="nn">pygments.formatters</span> <span class="kn">import</span> <span class="n">HtmlFormatter</span> <span class="n">code</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">__file__</span><span class="p">)</span><span class="o">.</span><span class="n">read</span><span class="p">()</span> <span class="k">print</span> <span class="n">highlight</span><span class="p">(</span><span class="n">code</span><span class="p">,</span> <span class="n">PythonLexer</span><span class="p">(),</span> <span class="n">HtmlFormatter</span><span class="p">())</span> <span class="c">#print HtmlFormatter().get_style_defs(&#39;.highlight&#39;)</span> </pre></div>

of course relevant css is required which you can see in my blogs css file.

On another level, pypy does something similar with its translator (and i'm not talking about lexing).. Watch the few minutes leading up to 29min,50 seconds

page divider

Random Quote