How to create/modify a jupyter notebook from code (python)?

后端 未结 2 1888
既然无缘
既然无缘 2021-02-07 13:01

I am trying to automate my project create process and would like as part of it to create a new jupyter notebook and populate it with some cells and content that I usually have i

相关标签:
2条回答
  • 2021-02-07 13:12

    You can do it using nbformat. Below an example taken from 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)
    
    0 讨论(0)
  • 2021-02-07 13:33

    This is absolutely possible. Notebooks are just json files. This notebook for example is just:

    {
     "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
    }
    

    While messy it's just a list of cell objects. I would probably create my template in an actual notebook and save it rather than trying to generate the initial template by hand. If you want to add titles or other variables programmatically, you could always copy the raw notebook text in the *.ipynb file into a python file and insert values using string formatting.

    0 讨论(0)
提交回复
热议问题