是否有IPython笔记本API?

前端之家收集整理的这篇文章主要介绍了是否有IPython笔记本API?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我想从python脚本生成几个笔记本.是否有编写IPython笔记本的API?

最佳答案
有,你可以这样做:

  1. import io
  2. from IPython.nbformat import current
  3. def convert(py_file,ipynb_file):
  4. with io.open(py_file,'r',encoding='utf-8') as f:
  5. notebook = current.reads(f.read(),format='py')
  6. with io.open(ipynb_file,'w',encoding='utf-8') as f:
  7. current.write(notebook,f,format='ipynb')
  8. convert('test.py','test.ipynb')

但它并不那么聪明,它会将python文件中的所有代码放入一个IPython Notebook单元格中.但是你总是可以做一些解析.

  1. import io
  2. import re
  3. from IPython.nbformat import current
  4. def parse_into_cells(py_file):
  5. with io.open(py_file,encoding='utf-8') as f:
  6. data = f.readlines()
  7. in_cell = True
  8. cell = ''
  9. for line in data:
  10. if line.rstrip() == '':
  11. # If a blank line occurs I'm out of the current cell
  12. in_cell = False
  13. elif re.match('^\s+',line):
  14. # Indentation,so nope,I'm not out of the current cell
  15. in_cell = True
  16. cell += line
  17. else:
  18. # Code at the beginning of the line,so if I'm in a cell just
  19. # append it,otherwise yield out the cell and start a new one
  20. if in_cell:
  21. cell += line
  22. else:
  23. yield cell.strip()
  24. cell = line
  25. in_cell = True
  26. if cell != '':
  27. yield cell.strip()
  28. def convert(py_file,ipynb_file):
  29. # Create an empty notebook
  30. notebook = current.reads('',format='py')
  31. # Add all the parsed cells
  32. notebook['worksheets'][0]['cells'] = list(map(current.new_code_cell,parse_into_cells(py_file)))
  33. # Save the notebook
  34. with io.open(ipynb_file,format='ipynb')
  35. convert('convert.py','convert.ipynb')

编辑:解释解析

在前面的代码中,只要在模块级指令(函数,变量或类定义,导入等)之前出现空行,就会触发单元格拆分.这就是每当我看到一条没有缩进的行并且前面有一个空行时).所以:

  1. import time
  2. import datetime

将只是一个单元格,但是:

  1. import time
  2. import datetime

将是两个细胞,也是

  1. class Test(objet):
  2. def __init__(self,x):
  3. self.x = x
  4. def show(self):
  5. print(self.x)
  6. class Foo(object):
  7. pass

将是两个单元格,因为只有两个顶级定义(没有缩进的行)前面有一个空行(文件中的第一行被认为前面有一个空行,因为它必须启动一个新单元格) .

猜你在找的Python相关文章