Skip to article frontmatterSkip to article content

Generate MyST with Jupyter and insert it into content programmatically

While I’ve been converting my blog to use the new MyST engine, I discovered a useful MyST feature. It’s not yet possible to natively parse Jupyter Markdown outputs as MyST but there’s a workaround if you don’t mind generating a temporary file.

The trick is to write to a temporary file in your Jupyter cell, and then include the temporary output file with an {include} directive in your MyST markdown. This allows you to directly write MyST Markdown without worrying about what the MyST AST specification looks like.

For example, the following code cell writes some sample text to a .txt file in my MyST build directory.

from pathlib import Path
p = Path("../_build/txt/tmp.txt")
p.parent.mkdir(parents=True, exist_ok=True)
# Grab a list of all the filenames
files = list(p.rglob("../**/*.md"))
txt = "\n- ".join(files)
_ = p.write_text(txt)

And we can then include it in the page with MyST markdown like so:

```{include} ../_build/txt/tmp.txt
```

The page will be executed first, and afterward, the page will be parsed into MyST, thus using the temporary file we’ve included.