본문 바로가기

개발하자

코드(파이썬)에서 주피터 노트북을 생성/수정하는 방법은 무엇입니까?

반응형

코드(파이썬)에서 주피터 노트북을 생성/수정하는 방법은 무엇입니까?

프로젝트 생성 프로세스를 자동화하려고 합니다. 프로젝트 생성 프로세스의 일부로 새 주피터 노트북을 생성하여 모든 노트북에 일반적으로 있는 일부 셀과 컨텐츠(예: 가져오기, 제목 등)로 채우고 싶습니다.

파이썬을 통해 이것을 할 수 있나요?




이것은 절대적으로 가능하다. 노트북은 json 파일일 뿐입니다. 예를 들어 다음과 같습니다.

{
 "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 파일로 복사하고 문자열 형식을 사용하여 값을 삽입할 수 있습니다.




를 사용하여 이 작업을 수행할 수 있습니다. 아래의 예는 다음과 같습니다.

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)

반응형