python - Is there a IPython notebook api? -


i generate several notebooks python script. there api write ipython notebooks?

there is, can do:

import io ipython.nbformat import current  def convert(py_file, ipynb_file):     io.open(py_file, 'r', encoding='utf-8') f:         notebook = current.reads(f.read(), format='py')     io.open(ipynb_file, 'w', encoding='utf-8') f:         current.write(notebook, f, format='ipynb')  convert('test.py', 'test.ipynb') 

but it's not smart , place code python file 1 ipython notebook cell. can little bit of parsing.

import io import re ipython.nbformat import current  def parse_into_cells(py_file):     io.open(py_file, 'r', encoding='utf-8') f:         data = f.readlines()     in_cell = true     cell = ''     line in data:         if line.rstrip() == '':             # if blank line occurs i'm out of current cell             in_cell = false         elif re.match('^\s+', line):             # indentation, nope, i'm not out of current cell             in_cell = true             cell += line         else:             # code @ beginning of line, if i'm in cell             # append it, otherwise yield out cell , start new 1             if in_cell:                 cell += line             else:                 yield cell.strip()                 cell = line                 in_cell = true     if cell != '':         yield cell.strip()  def convert(py_file, ipynb_file):     # create empty notebook     notebook = current.reads('', format='py')     # add parsed cells     notebook['worksheets'][0]['cells'] = list(map(current.new_code_cell,                                                   parse_into_cells(py_file)))     # save notebook     io.open(ipynb_file, 'w', encoding='utf-8') f:         current.write(notebook, f, format='ipynb')  convert('convert.py', 'convert.ipynb') 

edit: explaining parsing

in previous code cell split triggered whenever blank line appears before module level instruction (function, variable or class definition, import, etc.). whenever see line not indented , preceded blank line). so:

import time import datetime 

will 1 cell, but:

import time  import datetime 

will 2 cells, , also

class test(objet):      def __init__(self, x):          self.x = x      def show(self):          print(self.x)  class foo(object):      pass 

will 2 cells since there 2 top level definitions (lines not indented) preceded blank line (first line in file considered preceded blank line because has start new cell).


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -