简体   繁体   中英

How to generate reST/sphinx source from python?

I'd like to generate documentation via reST, but don't want to write the reST source manually, but let a python script do that and then produce other formats (HTML, PDF) with sphinx.

Imagine I have a telephone book in binary format. Now I use a python script to parse this and generate a document with all the names and numbers:

  phone_book = PhonebookParser("somefile.bin")

  restdoc = restProducer.NewDocument()
  for entry in phone_book:
    restdoc.add_section( title = entry.name, body = entry.number )

  restdoc.write_to_file("phonebook.rst")

Then I would go on to invoke sphinx for generating pdf and html:

  > sphinx phonebook.rst -o phonebook.pdf
  > sphinx phonebook.rst -o phonebook.html

Is there a python module (aka restProducer in the example above) that offers an API for generating reST? Or is the best way to just dump reST markup via a couple of print statements?

  1. See Automatically Generating Documentation for All Python Package Contents .

  2. The upcoming Sphinx 1.1 release includes a sphinx-apidoc.py script.

EDIT:

Now that you have explained the problem a bit more, I'd say: go for the "dump reST markup via a couple of print statements" option. You seem to be thinking along those lines already. Why not try to implement a minimalistic restProducer ?

如果你想要docs-without-writing-docs(最多只能给你一个API参考而不是真正的文档),那么Sphinx的autosummaryautodoc扩展可能就是你所追求的。

If your purpose is to programmatically compose the document once, and be able to output in multiple formats, you could have a look at QTextDocument in PyQt Framework. It is an overkill, though.

from PyQt4.QtGui import *
import sys

doc = QTextDocument()
cur = QTextCursor(doc)

d_font = QFont('Times New Roman')
doc.setDefaultFont(d_font)

table_fmt = QTextTableFormat()
table_fmt.setColumnWidthConstraints([
    QTextLength(QTextLength.PercentageLength, 30),
    QTextLength(QTextLength.PercentageLength, 70)
    ])
table = cur.insertTable(5,2, table_fmt)
cur.insertText('sample text 1')
cur.movePosition(cur.NextCell)
cur.insertText('sample text 2')

# Print to a pdf file
# QPrinter: Must construct a QApplication before a QPaintDevice
app = QApplication(sys.argv)
printer = QPrinter(QPrinter.HighResolution)
printer.setOutputFormat(QPrinter.PdfFormat)
printer.setOutputFileName('sample.pdf')

# Save to file
writer = QTextDocumentWriter()
writer.setFormat(writer.supportedDocumentFormats()[1])
writer.setFileName('sample.odt')
writer.write(doc)

QTextDocumentWriter supports plaintext, html and ODF. QPrinter can be used to print to a physical printer or to a PDF file.

However, templating engines like Jinja2 as you mentioned is a neater way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM