Thursday, February 10, 2011

Syntax-Highlighting Python Code in Blogger using Style Sheets (CSS)

I want nicely-formatted, syntax-highlighted Python code interspersed with regular text. So:

  • In Blogger, I edited my Template, which is a style sheet with fancy extra stuff.
  • I went to the Python website and used Google Chrome's Developer Tools to view the page's style sheets.
  • I copied a short snippet of HTML into my blog post, making sure to add the necessary style sheet entries into my Template.
Here's a test of that:

>>> # try to access an undefined variable 
... n 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
NameError: name 'n' is not defined 

So, how did it go?

It looks good! I'm excited. The next step is to import the entire Python style sheet, and find a tool that'll convert snippets of Python code (from a file, or straight from the interpreter) into HTML.

Yay!

first

First post!

Here's a program, the HTML for which was generated with this recipe.

#!/usr/bin/env python

class HelloWorld():
    "A class to welcome you."

    def __init__(self,name):

        self.name = name

    def speak(self):

        print("Hello world, and %s in particular.\n" % \
                  (self.name))

if __name__ == "__main__":

    a = HelloWorld('ustinjay')
    a.speak()

Hello world, and ustinjay in particular.

After adding a style-sheet definition of pre to my blog's Template, which I got from the Python site, the background turned yellow. Before this, the background was plain white.