[Doc-SIG] simple use of docutils

David Goodger goodger@users.sourceforge.net
Thu, 10 Oct 2002 23:08:41 -0400


Michael Hudson wrote:
> I have an application where I want to programmatically use docutils.
> 
> So, I have a chuck of text (or a file, both are equally easy) in rst
> format that I want to turn into html (again, either a file, or as
> text).
> 
> This doesn't seem to be totally straightforward.

Questions and constructive suggestions are always appreciated.

> Clearly, I haven't really read the docs.

That's understandable, since there are none yet for what you're doing.
But you must have read the source to get this far.  Look at the
docstrings of the classes you're using and their __init__ methods for
details.  I've employed "attribute docstrings" liberally, in
anticipation of future tool support.

> I have code like this:
> 
>     from docutils.core import Publisher
>     from docutils.io import FileInput
> 
>     pub = Publisher(source=FileInput(None, source_path=filename),
>                     destination=htname)

What is "htname"?  The "destination" parameter has to be a
docutils.io.Output instance, such as FileOutput or StringOutput.

>     pub.set_options()
>     pub.set_reader('standalone', None, 'restructuredtext')
>     pub.set_writer('html')
>     pub.publish()
> 
> But that's not enough -- I have to cook up mythical 'option' objects
> from somewhere.

Just replace "pub.set_options()" with::

    options = pub.set_options()

"Publisher.set_options()" sets *and* returns the option values object.
You'll need to pass the options object to the I/O instantiators.  This
code should work (assuming you want a string return value)::

    from docutils.core import Publisher
    from docutils.io import FileInput, StringOutput

    pub = Publisher()
    options = pub.set_options()
    pub.source = FileInput(options, source_path=filename)
    pub.destination = StringOutput(options)
    pub.set_reader('standalone', None, 'restructuredtext')
    pub.set_writer('html')
    output = pub.publish()

> Is there an easy way of doing what I want?

The "docutils.core.publish()" convenience function is an easy way to
get file-to-file processing.  The to-do list has an entry for a
string-to-string processing convenience function, which I can whip up
quickly if it will help.  But I can't make one for every possible
combination; that's up to the developer.

> There should be.

The standard disclaimer applies: if something isn't there, it's either
because nobody has needed it yet or because nobody has had time to add
it yet.  Patches are welcome!

-- 
David Goodger  <goodger@users.sourceforge.net>  Open-source projects:
  - Python Docutils: http://docutils.sourceforge.net/
    (includes reStructuredText: http://docutils.sf.net/rst.html)
  - The Go Tools Project: http://gotools.sourceforge.net/