Search code examples
htmlrestructuredtextdocutils

How to use docutils to create HTML from reStructuredText?


I have written simple program to convert reStructuredText to html

from docutils.core import publish_string

input_string = ("Heading\n"
                "=======\n"
                "\n"
                "1. With 24 widgets pull a **long** one;\n"
                "2. with fewer, push a **wide** one.\n")

html = publish_string(input_string)
print(html)

But the output is:

<document ids="heading" names="heading" source="<string>" title="Heading">
    <title>
        Heading
    <enumerated_list enumtype="arabic" prefix="" suffix=".">
        <list_item>
            <paragraph>
                With 24 widgets pull a 
                <strong>
                    long
                 one;
        <list_item>
            <paragraph>
                with fewer, push a 
                <strong>
                    wide
                 one.

It is clearly trying, but am I missing a parameter? Do I need to specify the conversion required, e.g. reader, writer or parser?

It works perfectly when I run form the command line using

rst2html.py <input file> <output file>

Solution

  • I think I had the answer in the question :(

    I needed the writer_name parameter

    from docutils.core import publish_string
    
    input_string = ("Heading\n"
                    "=======\n"
                    "\n"
                    "1. With 24 widgets pull a **long** one;\n"
                    "2. with fewer, push a **wide** one.\n")
    
    html = publish_string(input_string, writer_name='html')
    
    print(html)