Ross Wan's World!

Python, Ajax, PHP and Linux.

Posts Tagged ‘reStructuredText’

reStructuredText: 自动处理 rst2html

Posted by Ross Wan 于 2011/08/19

因为经常都会使用到 reStructuredText,文档,Blog…等等.所以写了个自动处理 rst2html 的脚本myrst2html.py(Python 3.2):

#!/bin/python3
# coding=utf8

from docutils.core import publish_string
import sys, os, getopt

def get_last_modified_rst(path='.'):
    real_path = os.path.split(path)[0]
    last_modified_rst = ''
    last_modified = -1
    for rst in (x for x in os.listdir(path) if os.path.isfile(os.path.join(real_path,x)) and os.path.splitext(x)[1].lower()=='.rst'):
        rst = os.path.join(real_path, rst)
        rst_modified = os.path.getmtime(rst)
        if rst_modified > last_modified:
            last_modified = rst_modified
            last_modified_rst = rst
    return  last_modified_rst

def rst2html(rst_filename, target_filename=None):
    print(rst_filename)
    rst_file = open(rst_filename)
    print(1)
    source = rst_file.read()
    print(2)
    rst_file.close()
    print('Source: %s' % rst_filename)
    target_filename = target_filename and target_filename or os.path.splitext(rst_filename)[0]+'.html'
    target_file = open(target_filename, 'w')
    print('Target: %s' % target_filename)
    target_html = publish_string(
        source=source,
        writer_name='html',
        settings_overrides={'output_encoding': 'unicode'}
    )
    target_file.write(target_html)
    target_file.close()
    print('Done!')

def main():
    try:
        optlist, args = getopt.getopt(sys.argv[1:], '')
        rst_filename, target_filename = None, None
        if not args:
            last_rst = get_last_modified_rst()
            rst_filename = last_rst
        else:
            rst_filename, target_filename = (args + [None])[:2]
        rst2html(rst_filename, target_filename)
    except Exception as e:
        print(e)

if __name__ == '__main__':
    main()

执行方式:

python3 myrst2html.py [rst_file] [target_file]

参数 rst_file 和 target_file 分别是要转换的 rst 文件和转换的目标 html 文件.如果没提供 target_file, 则自动以 rst_file 命名目标文件;如果两个参数都不提供,则自动查找当前目录最后修改的 rst 文件,然后进行转换 :>

Have fun :)

Posted in Python, Uncategorized | Tagged: , , , | Leave a Comment »

好用的文档工具:reStructuredText

Posted by Ross Wan 于 2008/09/09

对于文档,最困难的就是排版,以及规范的格式。而 reStructuredText 就可以解决这个问题。它可以将纯文本重构建成格式规范的文档,输出成 html、xml、Latex 或者 PDF。妳只需要简单学习一下 reStructedText 的语法标记来编写那个纯文本即可。

reStructuredText 的学习曲线一点也不高,它跟 Python 的语法有点相近,主要通过缩进来定义元素。具体可以看看官网的文档:

中文文档可以参考《reStructuredText 简明教程》,由 Laurence 编写,Kardinal 翻译过来的:

编写好的源文档,需要使用一个 Python 工具 docutils 将其转化成 Html 或者 Latex 等等:(以在 Archlinux 系统下生成 Html 文件为例)

# pacman -Ss docutils

$ rst2html.py source.rst dest.html

这样就可以将 source.rst 纯文本文件转化成 HTML 格式的 dest.html 文档。

Posted in Archlinux, Python | Tagged: , , | Leave a Comment »