[Docpie]

Fork me on GitHub

序列化


from docpie import docpie
pie = Docpie(__doc__)

你可能觉得Docpie的解析过程略慢。你可以将其序列化,然后在任何你需要的地方载入。

pie.convert_2_dict() 可以将 Docpie 实例转为一个字典,然后你就可以保存为JSON格式了。用 Docpie.convert_2_docpie(dic) 来把这个字典回转为实例。

注意: 如果你传递了 extra 参数或调用过 set_auto_handler 方法,这部分信息会丢失,因为JSON无法保存一个可回调对象。你需要在反序列化后使用 set_config(extra={...}) 或者 set_auto_handler

这里是搭配 pickle 的完整示例。

开发:

"""
This is my cool script!

Usage: script.py [options] (--here|--there)

Options:
  --here
  --there
  -h, --help
  -v, --version

Have fun then.
"""

import json
try:
    import cPickle as pickle
except ImportError:    # py3 maybe
    import pickle
from docpie import Docpie


pie = Docpie(__doc__)

with open('myscript.docpie.pickle', 'wb') as pkf:
    pickle.dump(pie, pkf)

# omit `encoding` if you're using python2
with open('myscript.docpie.json', 'w', encoding='utf-8') as jsf:
    json.dump(pie.convert_2_dict(), jsf)

发布:

"""
This is my cool script!

Usage: script.py [options] (--here|--there)

Options:
  --here
  --there
  -h, --help
  -v, --version

Have fun then.
"""

import os
import json
try:
    import cPickle as pickle
except ImportError:    # py3 maybe
    import pickle
from docpie import Docpie

pie = None

if os.path.exists('myscript.docpie.pickle'):
    with open('myscript.docpie.pickle', 'rb') as pkf:
        try:
            pie = pickle.load(pkf)
        except BaseException:
            pass

if pie is None and os.path.exists('myscript.docpie.json'):
    # omit `encoding` if you're using python2
    with open('myscript.docpie.json', 'r', encoding='utf-8') as jsf:
        try:
            pie = Docpie.convert_2_docpie(json.load(jsf))
        except BaseException:
            pass
        else:
            # set extra if you have changed `extra` before
            pie.set_config(extra={})

if pie is None:
    pie = Docpie(__doc__)

print(pie.docpie())

如果你喜欢这个项目,可以买我一杯啤酒,让我做的更好! | Flattr this

侧栏导航