nbpy.py
47 lines
| 1.3 KiB
| text/x-python
|
PythonLexer
Brian E. Granger
|
r4392 | """Read and write notebooks as regular .py files.""" | ||
Brian E. Granger
|
r4401 | from .rwbase import NotebookReader, NotebookWriter | ||
from .nbbase import new_code_cell, new_worksheet, new_notebook | ||||
Brian E. Granger
|
r4392 | |||
class PyReader(NotebookReader): | ||||
Brian E. Granger
|
r4401 | def reads(self, s, **kwargs): | ||
Brian E. Granger
|
r4392 | lines = s.splitlines() | ||
cells = [] | ||||
cell_lines = [] | ||||
for line in lines: | ||||
Brian E. Granger
|
r4401 | if line.startswith(u'# <codecell>'): | ||
code = u'\n'.join(cell_lines) | ||||
code = code.strip(u'\n') | ||||
Brian E. Granger
|
r4392 | if code: | ||
cells.append(new_code_cell(input=code)) | ||||
cell_lines = [] | ||||
else: | ||||
cell_lines.append(line) | ||||
ws = new_worksheet(cells=cells) | ||||
nb = new_notebook(worksheets=[ws]) | ||||
return nb | ||||
class PyWriter(NotebookWriter): | ||||
Brian E. Granger
|
r4401 | def writes(self, nb, **kwargs): | ||
Brian E. Granger
|
r4392 | lines = [] | ||
Brian E. Granger
|
r4401 | for ws in nb.worksheets: | ||
for cell in ws.cells: | ||||
if cell.cell_type == 'code': | ||||
input = cell.input | ||||
lines.extend([u'# <codecell>',u'']) | ||||
Brian E. Granger
|
r4392 | lines.extend(input.splitlines()) | ||
Brian E. Granger
|
r4401 | lines.append(u'') | ||
return unicode('\n'.join(lines)) | ||||
Brian E. Granger
|
r4392 | |||
_reader = PyReader() | ||||
_writer = PyWriter() | ||||
reads = _reader.reads | ||||
read = _reader.read | ||||
write = _writer.write | ||||
writes = _writer.writes | ||||