本文介绍了从 Python 写入 Jupyter Notebook的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将 Python 脚本写入 iPython Notebook?

Is it possible for a Python script to write into a iPython Notebook?

with open("my_notebook.ipynb", "w") as jup:
     jup.write("print(\"Hello there!\")")

如果有这样的包,我还可以控制笔记本中单元格的拆分方式吗?

If there's some package for doing so, can I also control the way cells are split in the notebook?

我正在设计一个软件工具(执行一些优化)来准备一个 iPython 笔记本,它可以在一些执行科学计算的服务器上运行.

I'm designing a software tool (that carries out some optimization) to prepare an iPython notebook that can be run on some server performing scientific computations.

我知道一个相关的解决方案是输出到 Python 脚本并使用 %load my_python_script.py 将其加载到 iPython Notebook 中.但是,这需要用户输入我希望避免的内容.

I understand that a related solution is to output to a Python script and load it within a iPython Notebook using %load my_python_script.py. However, that involves a user to type stuff that I would ideally like to avoid.

推荐答案

查看 nbformat 存储库在 Github 上.那里显示了参考实现.

Look at the nbformat repo on Github. The reference implementation is shown there.

来自他们的文档

Jupyter (né IPython) 笔记本文件是简单的 JSON 文档,包含文本、源代码、富媒体输出和元数据.文档的每一段都存储在一个单元格中.

听起来您也想以编程方式创建笔记本,因此您应该使用 NotebookNode 对象.

It also sounds like you want to create the notebook programmatically, so you should use the NotebookNode object.

对于代码,类似的东西应该可以满足您的需求.new_cell_code 如果您有代码单元格而不是纯文本单元格,则应该使用.文本单元格应使用现有的 Markdown 格式.

For the code, something like, should get you what you need. new_cell_code should be used if you have code cells versus just plain text cells. Text cells should use the existing markdown formatting.

import nbformat

notebook = nbformat.v4.new_notebook()


text = """Hello There """



notebook['cells'] = [nbformat.v4.new_markdown_cell(text)]
notebook= nbformat.v4.new_notebook()
nbformat.write(notebook,'filename.ipynb')

这篇关于从 Python 写入 Jupyter Notebook的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-20 22:19