使用Quarto include指令报错,合并代码却正常的问题咨询
解决Quarto中Python代码块使用
{{< include >}}指令的语法错误问题 问题背景
在Quarto 1.2.313及开发版1.3.124中,在Python代码块内使用{{< include inner.py >}}引入外部文件时,执行quarto render outer.qmd会触发Python语法错误;但将外部文件代码直接复制到代码块中,渲染则完全正常。
报错信息
Starting python3 kernel...Done Executing 'outer.ipynb' Cell 1/1...ERROR: An error occurred while executing the following cell: ------------------ {{< include inner.py >}} ------------------ Cell In [1], line 1 {{< include inner.py >}} ^ SyntaxError: invalid syntax SyntaxError: invalid syntax (2193102924.py, line 1)
问题原因
{{< include >}}是Quarto的Pandoc短代码,其替换逻辑在Quarto的模板渲染阶段执行。但当你指定jupyter: python3引擎时,Quarto的处理流程是:
- 先将.qmd文件转换为.ipynb格式(此时短代码未被替换,直接保留在代码单元格中)
- 启动Python内核执行.ipynb的代码单元格
- Python内核无法识别
{{< >}}这种模板语法,因此抛出语法错误
而直接复制代码到代码块时,转成.ipynb的是合法Python代码,内核可以正常执行。
解决方案
方案1:使用Quarto代码单元格#| include选项(推荐)
替换原有的短代码引入方式,改用Quarto为代码单元格提供的include选项,该选项会在预处理阶段就将外部文件内容导入代码块,适配所有引擎:
修改outer.qmd的Python代码块:
--- title: "test" format: html: code-fold: true jupyter: python3 --- Some text. ```{python} #| label: fig-test #| fig-cap: "test" #| include: inner.py
### 方案2:改用`engine: python`而非Jupyter引擎 如果你的代码不需要交互式运行(比如不需要生成可交互的ipynb文件),可以在YAML头部指定直接使用Python脚本引擎,此时Quarto会在预处理阶段替换`{{< include >}}`短代码: ```yaml --- title: "test" format: html: code-fold: true engine: python --- Some text. ```{python} #| label: fig-test #| fig-cap: "test" {{< include inner.py >}}
### 方案3:手动预处理替换短代码(不推荐) 若必须使用Jupyter引擎,可先通过Quarto预处理生成替换后的Markdown文件,再基于该文件渲染: ```bash # 先生成替换短代码后的md文件 quarto render outer.qmd --to markdown # 再基于md文件渲染为html quarto render outer.md --to html
此方法步骤繁琐,仅作为备选方案。
内容的提问来源于stack exchange,提问作者gcl
相关产品推荐
相关产品推荐

