Skip to content

Instantly share code, notes, and snippets.

@josephmosby
Created May 16, 2012 20:40
Show Gist options
  • Save josephmosby/2713759 to your computer and use it in GitHub Desktop.
Save josephmosby/2713759 to your computer and use it in GitHub Desktop.
The Weeds of Github

The Weeds of Markdown

Consider this a first experiment in John Gruber's Markdown. For the uninitiated, Markdown is a syntax combined with a tool that allows you to take specially formatted text and translate it into HTML. Though most out-of-the-box blogging platforms handle this conversion for bloggers, it gets a bit dicier as more customization is added.

I'm not going to get into the weeds of Markdown syntax, as Mr. Gruber's explanation is far better than mine. Instead, I'm going to do a brief intro on how to write a Python script to perform the task you'll most often need to do with Markdown: convert .md files to browser-readable HTML.

pip install markdown

The Markdown libraries are now standard in the PyPi repository and can be installed through pip (or your method of choice). Markdown has no dependencies and is a relatively quick install.

import markdown
import codecs
md_file = codecs.open('my_file.md', mode='r', encoding='utf8')
md_input = md_file.read()
html = markdown.markdown(md_input)

Markdown is a little bit picky here. You can simply feed a text file to a Markdown converter and return the value, but Markdown will only accept Unicode input. If your input is encoded in another format, you'll need to decode it first before dealing with it. I would forget this nuance and then be frustrated when my script didn't work, so the script we'll create here will compensate automatically.

html_output = codecs.open('my_html.html', mode='w', encoding='utf8')
html_output.write(html)

Writing the HTML is as easy as a file.write(input) Python method. The output is already internally parsed as HTML, and we're just dumping that output into a file.

This is obviously useful if you're crafting your own blog HTML, but what if you don't own your own blog? What if you're not going through the process of a full blog maintenance but still have a few things you'd like to say? Github is gracious enough to parse Markdown in gists and give you an ad-hoc blogging platform tied to your Github account. Post away, share it out on Twitter, accept comments from Githubbers... and manage none of the infrastructure yourself.

Give Markdown a try, and thank Mr. Gruber if you dig it. I hate dealing with HTML at this level of detail, so Markdown is exactly what I need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment