Skip to content

Commit bdafcd6

Browse files
committed
use nbconvert to write scripts
1 parent 43280f8 commit bdafcd6

File tree

2 files changed

+23
-13
lines changed

2 files changed

+23
-13
lines changed

jupyter_sphinx/execute.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import os
44
from pathlib import Path
5+
from logging import Logger
56

67
from sphinx.transforms import SphinxTransform
78
from sphinx.errors import ExtensionError
@@ -40,6 +41,20 @@
4041
)
4142

4243

44+
class LoggerAdapterWrapper(Logger):
45+
"""Wrap a logger adapter, while pretending to be a logger.
46+
47+
Workaround of https://github.com/ipython/traitlets/issues/606
48+
"""
49+
def __init__(self, wrapped):
50+
self._wrapped = wrapped
51+
52+
def __getattribute__(self, attr):
53+
if attr == "_wrapped":
54+
return object.__getattribute__(self, attr)
55+
return self._wrapped.__getattribute__(attr)
56+
57+
4358
class JupyterKernel(Directive):
4459
"""Specify a new Jupyter Kernel.
4560
@@ -262,20 +277,16 @@ def write_notebook_output(notebook, output_dir, notebook_name, location=None):
262277
resources,
263278
os.path.join(output_dir, notebook_name + ".ipynb"),
264279
)
265-
# Write a script too. Note that utf-8 is the de facto
266-
# standard encoding for notebooks.
267-
ext = notebook.metadata.get("language_info", {}).get("file_extension", None)
268-
if ext is None:
269-
ext = ".txt"
270-
js.logger.warning(
271-
"Notebook code has no file extension metadata, " "defaulting to `.txt`",
272-
location=location,
273-
)
274-
contents = "\n\n".join(cell.source for cell in notebook.cells)
275280

276-
notebook_file = notebook_name + ext
281+
# Write a script too. Due to https://github.com/ipython/traitlets/issues/606
282+
# we're using a wrapper to make a LoggerAdapter look like a wrapper.
283+
exporter = nbconvert.exporters.ScriptExporter(log=LoggerAdapterWrapper(js.logger))
284+
contents, resources = exporter.from_notebook_node(notebook)
285+
286+
notebook_file = notebook_name + resources['output_extension']
277287
output_dir = Path(output_dir)
278-
(output_dir / notebook_file).write_text(contents, encoding = "utf8")
288+
# utf-8 is the de-facto standard encoding for notebooks.
289+
(output_dir / notebook_file).write_text(contents, encoding="utf8")
279290

280291

281292
def contains_widgets(notebook):

tests/test_execute.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,6 @@ def doctree(
5959
app.build()
6060

6161
doctree = app.env.get_and_resolve_doctree("index", app.builder)
62-
6362
if return_warnings:
6463
return doctree, warnings.getvalue()
6564
else:

0 commit comments

Comments
 (0)