bebraw
11/12/2011 - 11:23 AM

pandoc.py

import subprocess
import sys

def convert(source, from_format, to_format):
    # original version: http://osiux.com/html-to-restructured-text-in-python-using-pandoc
    # supported formats at http://johnmacfarlane.net/pandoc/
    # raises OSError if pandoc is not found!
    p = subprocess.Popen(['pandoc', '--from=' + from_format, '--to=' + to_format],
        stdin=subprocess.PIPE, stdout=subprocess.PIPE
    )

    if sys.version_info[0] == 3:
        return p.communicate(bytes(source, 'UTF-8'))[0]

    return p.communicate(source)[0]

# example
readme = open('README.md').read() # might want to use "with" to make sure it gets closed
output = convert(readme, 'markdown', 'rst')