问题描述
在nbonvert版本6下,模板现在是包含多个文件的目录。这些模板可以存在于不同位置,具体取决于平台。
Raspbian:
['/home/pi/.local/share/jupyter/nbconvert/templates','/usr/local/share/jupyter/nbconvert/templates','/usr/share/jupyter/nbconvert/templates']
带有Pyenv的OS X:
['/Users/ac/Library/Jupyter/nbconvert/templates','/Users/ac/.pyenv/versions/3.8.5/Python.framework/Versions/3.8/share/jupyter/nbconvert/templates','/usr/share/jupyter/nbconvert/templates']
我正在尝试在多个不同的平台上同步我的模板,并希望指定一个自定义位置。
This post从2年前开始似乎是正确的,但似乎适用于nbconvert的V5-该方法已将名称从template_path
更改为template_paths
。
我已经尝试过使用上面提到的链接中建议的解决方案,将其放置在已知位置之一时可以使用该模板。当尝试按建议指定自定义位置时,我最终遇到此错误:
jinja2.exceptions.TemplateNotFound: null.j2
我怀疑通过将路径设置为/path/to/.jupyter/templates/my_template/
,我会完全覆盖所有其他模板位置,并丢失模板扩展的null.j2
模板。我在最后添加了模板,但有可能导致此错误。
The docs for V6 config files并没有太大帮助:
TemplateExporter.template_paths : List
Default: ['.']
No description
和
PythonExporter.template_paths : List
Default: ['.']
No description
在Git Repo上有一个long thread from May 2019对此进行了讨论,但是我不太明白最终结论是什么。
我的自定义Python模板:
{%- extends 'null.j2' -%}
## set to python3
{%- block header -%}
#!/usr/bin/env python3
# coding: utf-8
{% endblock header %}
## remove cell counts entirely
{% block in_prompt %}
{% if resources.global_content_filter.include_input_prompt -%}
{% endif %}
{% endblock in_prompt %}
## remove markdown cells entirely
{% block markdowncell %}
{% endblock markdowncell %}
{% block input %}
{{ cell.source | ipython2python }}
{% endblock input %}
## remove magic statement completely
{% block codecell %}
{{'' if "get_ipython" in super() else super() }}
{% endblock codecell%}
解决方法
Issue #1428 on the Git Repo包含此解决方案的基础。
从v5到v6的从头开始/最近升级:
- 在
~/.jupyter
中为V6生成当前的最新配置文件
$ jupyter nbconvert --generate-config
- 编辑配置文件
~/.jupyter/jupyter_nbconvert_config.py
以添加以下行:
from pathlib import Path
# set a custom path for templates in
c.TemplateExporter.extra_template_basedirs
my_templates = Path('~/my/custom/templates').expanduser().absolute()
# add the custom path to the extra_template_basedirs
c.TemplateExporter.extra_template_basedirs = [my_templates]
-
将模板添加到
~/my/custom/templates
目录- 每个模板必须位于其自己的子目录(
/my/custom/templates/foo_template
) - 每个模板必须包含一个
conf.json
和index.py.j2
文件。索引是实际的模板。参见下面的示例
- 每个模板必须位于其自己的子目录(
-
运行nbconvert:
$ jupyter nbconvert --to python --template my_custom_template foo.ipynb
conf.json
基本示例
{
"base_template": "base","mimetypes": {
"text/x-python": true
}
}
index.py.j2
示例
{%- extends 'null.j2' -%}
## set to python3
{%- block header -%}
#!/usr/bin/env python3
# coding: utf-8
{% endblock header %}
## remove cell counts entirely
{% block in_prompt %}
{% if resources.global_content_filter.include_input_prompt -%}
{% endif %}
{% endblock in_prompt %}
## remove markdown cells entirely
{% block markdowncell %}
{% endblock markdowncell %}
{% block input %}
{{ cell.source | ipython2python }}
{% endblock input %}
## remove magic statement completely
{% block codecell %}
{{'' if "get_ipython" in super() else super() }}