7

我想通过 reST 生成文档,但不想手动编写 reST 源代码,而是让 python 脚本来做,然后用 sphinx 生成其他格式(HTML、PDF)。

想象一下,我有一本二进制格式的电话簿。现在我使用 python 脚本来解析它并生成一个包含所有名称和数字的文档:

  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")

然后我会继续调用 sphinx 来生成 pdf 和 html:

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

是否有提供 API 用于生成 reST 的 python 模块(在上面的示例中也称为 restProducer)?还是通过几个打印语句转储 reST 标记的最佳方法?

4

3 回答 3

5
  1. 请参阅为所有 Python 包内容自动生成文档

  2. 即将发布的Sphinx 1.1版本包含一个sphinx-apidoc.py脚本。

编辑:

现在您已经对问题进行了更多解释,我想说:选择“通过几个打印语句转储 reST 标记”选项。你似乎已经在考虑这些问题了。为什么不尝试实现简约restProducer

于 2011-03-13T12:17:32.410 回答
3

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

于 2011-03-13T11:55:16.200 回答
0

如果您的目的是以编程方式编写文档一次,并且能够以多种格式输出,您可以查看 PyQt Framework 中的 QTextDocument。不过,这有点矫枉过正。

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支持纯文本、html 和 ODF。QPrinter可用于打印到物理打印机或 PDF 文件。

但是,您提到的 Jinja2 之类的模板引擎是一种更简洁的方法。

于 2014-11-19T09:31:28.320 回答