Running Code

Overview

Quarto supports executable code blocks within markdown. This allows you to create fully reproducible documents and reports—the code required to produce your output is part of the document itself, and is automatically re-run whenever the document is rendered.

There are currently two engines supported for running computations:

  • Jupyter, for running code from Python and many other languages.

  • Knitr, for running code from R.

Extensive customization of code chunk output is supported, including the ability to hide code and/or output as well as fold code (make it visible only on demand).

Code Blocks

Code blocks that use braces around the language name (e.g. ```{python}) are executable, and will be run by Quarto during render. Here are a couple of simple examples in Python and R to illustrate (the output produced by the code block is shown on the Output tab):

Python (Jupyter)

---
title: "Jupyter Document"
format: 
  html:
    code-background: true
jupyter: python3
---

```{python}
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.show()
```

```{python}
import pandas as pd
d = {'one' : [1., 2., 3., 4.],
     'two' : [4., 3., 2., 1.]}
df = pd.DataFrame(d)
df
```

The resulting document rendered from the source code in the `Code` tab using the Jupyter engine. At the top of the page is the title `Jupyter Document` in large text. There is a block of code with a gray background underneath the title. Underneath this block is a line plot of y = x. There is another code block with a gray background under this and a table underneath that.

Note that we added the code-background: true option to provide a background color for the code chunks (see the documentation on Code Block options for additional details on customizing code block output).

R (Knitr)

---
title: "Knitr Document"
format: 
  html:
    code-background: true
execute:
  warning: false
---

```{r}
library(ggplot2)
ggplot(airquality, aes(Temp, Ozone)) + 
        geom_point() + 
        geom_smooth(method = "loess", se = FALSE)
```

```{r}
summary(airquality)
```

The resulting document rendered from the source code in the `Code` tab using the Knitr engine. At the top of the page is the title `Knitr Document` in large text. There is a block of code with a gray background underneath the title. Underneath this block is a scatterplot of the `airquality` dataset fit with a polynomial regression line and overlaid with a grey ribbon representing the confidence interval. There is another code block with a gray background under this plot with the output of `summary(airquality)`.

Note that we added the execute: warning: false option to suppress printing of warnings. See Execution Options for additional details.

You can produce a wide variety of output types from executable code blocks, including:

  • Static plots (e.g. from matplotlib or ggplot2).

  • Interactive plots (e.g. from plotly or leaflet).

  • Tabular output (e.g. from printing R or Pandas data frames)

  • Plain text output (e.g. printing the results of statistical summaries).

Non-Executable Blocks

Note that code blocks that use convential markdown code block syntax (either ```python or ```{.python}) are not executable:

Code Block Syntax Executable?
```{python}
1 + 1
```
Yes
```python
1 + 1
```
No
```{.python}
1 + 1
```
No

Non-executable code blocks are printed but not executed.

Rendering

Markdown

Quarto will automatically run computations in any markdown document that contains executable code blocks. For example, the Python example shown above might be rendered with:

quarto render jupyter-document.qmd

The R example might have been rendered with:

quarto render knitr-document.qmd

Notebooks

The Python example above uses a markdown input file, Quarto can also render any Jupyter notebook (.ipynb):

quarto render jupyter-document.ipynb

Note that when rendering an .ipynb Quarto will not execute the cells within the notebook by default (the presumption being that you already executed them while editing the notebook). If you want to execute the cells you can pass the --execute flag to render:

quarto render jupyter-document.ipynb --execute

You can also specify this behavior within the notebook’s YAML front matter:

---
title: "My Document"
execute: true
jupyter: python3
---

Inline Code

Both Jupyter and Knitr support executing inline code within markdown (e.g. to allow narrative to automatically use the most up to date computations). The syntax for this varies across the engines.

Jupyter

To include executable expressions within markdown in a Jupyter notebook, you use IPython.display.Markdown to dynamically generate markdown from within an ordinary code cell. For example, if we have a variable radius we can use it within markdown as follows:

```{python}
#| echo: false
radius = 10
from IPython.display import display, Markdown
display(Markdown("""
## Circle

The radius of the circle is {radius}.
""".format(radius = radius)))
```

Note that we also include the echo: false option to ensure that the code used to generate markdown isn’t included in the final output.

Knitr

To include executable expressions within markdown for Knitr, enclose the expression in `r `. For example, if we have a variable radius we can use it within markdown as follows:

## Circle

The radius of the circle is `r radius`.

Engine Binding

Earlier we said that the engine used for computations was determined automatically. You may want to customize this—for example you may want to use the Jupyter R kernel rather than Knitr, or you may want to use Knitr with Python code (via reticulate).

Here are the basic rules for automatic binding:

Extension Engine Binding
.qmd

Use Knitr engine if an {r} code block is discovered within the file

Use Jupyter engine if an executable code block (e.g. {python}) is discovered within the file. The kernel used is determined based on the language of the first executable code block discovered.

Use no engine if no executable code blocks are discovered.

.ipynb Jupyter engine
.Rmd Knitr engine
.md No engine

You can override the engine used via the engine option. For example:

engine: jupyter
engine: knitr

You can also specify that no execution engine should be used via engine: markdown.

The presence of the knitr or jupyter option will also override the default engine:

knitr: true
jupyter: python3

Variations with additional engine-specific options also work to override the default engine:

knitr:
  opts_knit:
    verbose: true
jupyter:
  kernelspec:
    display_name: Python 3
    language: python
    name: python3

Fenced Echo

If you are writing a tutorial or documentation on using Quarto code blocks, you’ll likely want to include the fenced code delimiter (e.g. ```{python}) in your code output to emphasize that executable code requires that delimiter. You can do this using the echo: fenced option. For example, the following code block:

```{python}
#| echo: fenced
1 + 1
```

Will be rendered as:

```{python}
1 + 1
```
2

This is especially useful when you want to demonstrate the use of cell options. For example, here we demonstrate the use of the output and code-overflow options:

```{python}
#| echo: fenced
#| output: false
#| code-overflow: wrap
1 + 1
```

This code block appears in the rendered document as:

```{python}
#| output: false
#| code-overflow: wrap
1 + 1
```

Note that all YAML options will be included in the fenced code output except for echo: fenced (as that might be confusing to readers).

This behavior can also be specified at the document level if you want all of your executable code blocks to include the fenced delimiter and YAML options:

---
title: "My Document"
format: html
execute:
  echo: fenced
---

Unexecuted Blocks

Often you’ll want to include a fenced code block purely as documentation (not executable). You can do this by using two curly braces around the language (e.g. python, r, etc.) rather than one. For example:

```{{python}}
1 + 1
```

Will be output into the document as:

```{python}
1 + 1
```

If you want to show an example with multiple code blocks and other markdown, just enclose the entire example in 4 backticks (e.g. ````) and use the two curly brace syntax for code blocks within. For example:

````
---
title: "My document"
---

Some markdown content.

```{{python}}
1 + 1
```

Some additional markdown content.

````