Export and convert IPython notebooks. This function can export the current IPython history to a notebook file. For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
(self, s)
| 562 | ) |
| 563 | @line_magic |
| 564 | def notebook(self, s): |
| 565 | """Export and convert IPython notebooks. |
| 566 | |
| 567 | This function can export the current IPython history to a notebook file. |
| 568 | For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb". |
| 569 | """ |
| 570 | args = magic_arguments.parse_argstring(self.notebook, s) |
| 571 | outfname = os.path.expanduser(args.filename) |
| 572 | |
| 573 | from nbformat import write, v4 |
| 574 | from nbformat.sign import NotebookNotary |
| 575 | |
| 576 | cells = [] |
| 577 | hist = list(self.shell.history_manager.get_range()) |
| 578 | outputs = self.shell.history_manager.outputs |
| 579 | exceptions = self.shell.history_manager.exceptions |
| 580 | |
| 581 | if(len(hist)<=1): |
| 582 | raise ValueError('History is empty, cannot export') |
| 583 | |
| 584 | for session, execution_count, source in hist[:-1]: |
| 585 | cell = v4.new_code_cell(execution_count=execution_count, source=source) |
| 586 | |
| 587 | for output in outputs[execution_count]: |
| 588 | if output.output_type in {"out_stream", "err_stream"}: |
| 589 | text_data = [] |
| 590 | for mime_type, data in output.bundle.items(): |
| 591 | if isinstance(data, list): |
| 592 | text_data.extend(data) |
| 593 | else: |
| 594 | text_data.append(data) |
| 595 | full_text = "".join(text_data) |
| 596 | # Replace literal \n with actual newlines |
| 597 | full_text = full_text.replace("\\n", "\n") |
| 598 | normalized_text = [] |
| 599 | lines = full_text.split("\n") |
| 600 | for i, line in enumerate(lines): |
| 601 | if i < len(lines) - 1: |
| 602 | normalized_text.append(line + "\n") |
| 603 | elif line: # Last line only if it's not empty |
| 604 | normalized_text.append(line + "\n") |
| 605 | stream_output = v4.new_output("stream", text=normalized_text) |
| 606 | if output.output_type == "err_stream": |
| 607 | stream_output.name = "stderr" |
| 608 | cell.outputs.append(stream_output) |
| 609 | |
| 610 | elif output.output_type == "execute_result": |
| 611 | data_dict = {} |
| 612 | for mime_type, data in output.bundle.items(): |
| 613 | data_dict[mime_type] = data |
| 614 | cell.outputs.append( |
| 615 | v4.new_output( |
| 616 | "execute_result", |
| 617 | data=data_dict, |
| 618 | execution_count=execution_count, |
| 619 | ) |
| 620 | ) |
| 621 |
nothing calls this directly
no test coverage detected