我们如何在 iPython notebook 中使用 Plantuml UML 工具?它应该对我们有所帮助,因为 UML 图形在文书工作中经常使用。
在互联网上搜索了一些谷歌之后,我找到了一个在 iPython notebook 中使用 Asymptote 的优秀参考,然后我为 iPython notebook 创建了一个 Plantuml 扩展。下面是详细步骤:
从我的工作目录启动 iPython notebook。例如:$HOME/workshop。
# cd $HOME/workshop # ipython notebook --pylab inline
在 $HOME/workshop.eg:plantuml.py 创建一个扩展脚本
""" An Plantuml extension for generating UML figures from within ipython notebook. """ import os from IPython.core.magic import magics_class, cell_magic, Magics from IPython.display import Image, SVG @magics_class class Plantuml(Magics): @cell_magic def plantuml(self, line, cell): """Generate and display a figure using Plantuml. Usage: %java -jar plantuml.jar -tsvg filname """ self.filename = line self.code = cell with open(self.filename + ".plt", "w") as file: file.write(self.code) os.system("java -jar plantuml.jar -tsvg %s.plt" % self.filename) return SVG(filename=self.filename+".svg") def load_ipython_extension(ipython): ipython.register_magics(Plantuml)
从官网下载plantuml.jar到$HOME/workshop。
创建一个新的 iPython 笔记本,在单元格下方运行以加载扩展并使用该扩展:
%install_ext plantuml.py %reload_ext plantuml
创建一个植物细胞来测试结果。
%%plantuml figure1 @startuml Alice -> Bob: Authentication Request Bob --> Alice: Authentication Response @enduml
然后,来自 plantuml 的所有内容都将在 iPython notebook 中运行。
一些问题是:
- 如果 Plantuml 代码中有任何语法错误,则 Plantuml 的错误输出不会显示在 iPython notebook 中。如果 SVG 生成失败会很好,然后输出错误文本,否则将 SVG 文件输出到 notebook。
- 扩展使用的是 SVG 格式,不确定是否可以使用 PDF 或 PNG 格式。我也希望扩展 TiKz,但 pdflatex 总是输出 pdf 文件格式。我必须先使用 3rd-party 工具将其转换为 SVG 格式。这有点费时。