1st June, 2010

Generating HTML versions of reStructuredText files

Filed under: General,python — admin @ 1:37 pm

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.

4 Comments

  1. One minor suggestion for improvement: instead of using file_name[:-4] to strip off the extension, a more general solution would be to use os.path.splitext(file_name)[0].

    Comment by Daniel Harding — 01/06/2010 @ 6:15 pm

  2. One minor suggestion for improvement: instead of using file_name[:-4] to strip off the extension, a more general solution would be to use os.path.splitext(file_name)[0].

    Comment by Daniel Harding — 01/06/2010 @ 6:15 pm

  3. Not bad for having written quite nothing! The same can be achieved for server/common.py, server/passenger.py and server/models by creating the corresponding .rst files and then including them in index.rst under driver.

    Comment by junk yards — 08/08/2010 @ 9:01 pm

  4. Not bad for having written quite nothing! The same can be achieved for server/common.py, server/passenger.py and server/models by creating the corresponding .rst files and then including them in index.rst under driver.

    Comment by junk yards — 08/08/2010 @ 9:01 pm

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress