如何从代码(python)创建/修改jupyter笔记本?

时间:2016-07-05 01:04:06

标签: jupyter-notebook

我正在尝试自动化我的项目创建过程,并希望在其中创建一个新的jupyter笔记本并用一些单元格和内容填充它,我通常在每个笔记本中(即导入,标题等)

是否可以通过python执行此操作?

2 个答案:

答案 0 :(得分:14)

您可以使用 nbformat 执行此操作。以下是Creating an IPython Notebook programatically

的示例
import nbformat as nbf

nb = nbf.v4.new_notebook()
text = """\
# My first automatic Jupyter Notebook
This is an auto-generated notebook."""

code = """\
%pylab inline
hist(normal(size=2000), bins=50);"""

nb['cells'] = [nbf.v4.new_markdown_cell(text),
               nbf.v4.new_code_cell(code)]
fname = 'test.ipynb'

with open(fname, 'w') as f:
    nbf.write(nb, f)

答案 1 :(得分:3)

这绝对是可能的。笔记本只是json文件。这个 notebook例如只是:

{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Header 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2016-09-16T16:28:53.333738",
     "start_time": "2016-09-16T16:28:53.330843"
    },
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def foo(bar):\n",
    "    # Standard functions I want to define.\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Header 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.10"
  },
  "toc": {
   "toc_cell": false,
   "toc_number_sections": true,
   "toc_threshold": 6,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}

虽然凌乱,但它只是一个单元格对象列表。我可能会在实际笔记本中创建我的模板并保存它而不是尝试手动生成初始模板。如果要以编程方式添加标题或其他变量,可以始终将* .ipynb文件中的原始笔记本文本复制到python文件中,并使用字符串格式插入值。