Search code examples
pythonpython-3.xdocutils

Write reStructuredText t programmatically in Python


Is there any Python3.X library that helps to write rST file/text. I do not want to write rST file with manual styling with file.write(). I am looking for a library which makes it easier to create an rST file with different elements like bold, underline, tables.

Note: I do not want to read a rST file, rather I want to create a rST file programmatically


Solution

  • Use RstCloth to create RST-files via an easy Python API.

    from rstcloth import RstCloth
    
    d = RstCloth()
    d.title('Example Use')
    d.newline()
    d.h2('Contents')
    d.directive(name="contents", fields=[('local', ''), ('backlinks', 'None')])
    d.newline()
    d.h2('Code -- shebang')
    d.codeblock('#!/usr/bin/env')
    
    d.print_content()
    

    Result:

    ===========
    Example Use
    ===========
    
    Contents
    --------
    
    .. contents::
       :local:
       :backlinks: None
    
    Code -- shebang
    ---------------
    
    ::
    
       #!/usr/bin/env