Generating HTML versions of reStructuredText files

I wanted to quickly and easily convert a series of reStructured text documents into HTML equivalents. For reasons too dull to discuss here I couldn't just use rst2html.py and didn't want to go to the trouble of remembering enough bash syntax to write a shell script. So I thought that as long as docutils is written in Python it would only take a moment or two to knock up a script to do what I needed. Well yes, and no. The script itself is fairly simple;


from docutils import core



def convert_files(name_pattern):

    for file_name in glob.glob(name_pattern):

        source = open(file_name, 'r')

        file_dest = file_name[:-4] + '.html'

        destination = open(file_dest, 'w')

        core.publish_file(source=source, destination=destination, writer_name='html')

        source.close()

        destination.close()

The most useful line being the one where I call core.publish_file. But it wasn't immediately obvious from the docutils documentation what series of incantations would achieve my desired results. Luckily, after some time spent perusing the documents I came across this dissection of rst2html.py. This, in turn, lead me to the description of the Docutils Publisher, which lists the convenience functions available to work with the engine. The end result isn't particularly elegant but it does get the job done and I thought I would share it in case anyone else has a similar need in the future.