因为经常都会使用到 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 :)