Search code examples
pythonexecutionevaluationquarto

How can I include external Python scripts while executing their codes in Quarto?


I am rendering a Quarto markdown as a parent file (test.qmd in the MWE). By way of rendering, I am trying to include an external Python script (lm.py) in the parent file while executing the Python code, and refer to the result of the code (model in lm.py) in the parent file. However, I face a NameError as shown below, and I am unable to access the result from the parent file:

Executing 'test.ipynb'
  Cell 1/2...Done
  Cell 2/2...ERROR: 

An error occurred while executing the following cell:
------------------
print(model.summary())
------------------

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp\ipykernel_18968\3590939978.py in <module>
----> 1 print(model.summary())

NameError: name 'model' is not defined
NameError: name 'model' is not defined

Then, how can I include an external Python script while executing its codes when I render a Quarto markdown file?

MWE

test.qmd

---
format: pdf
execute:
  cache: false
---

```{python}
#| echo: true
#| eval: true
#| file: lm.py
```

```{python}
print(model.summary())
```

lm.py

import statsmodels.api as sm
import pandas as pd

mtcars = sm.datasets.get_rdataset('mtcars').data

model = sm.formula.ols('am ~ cyl + mpg', data = mtcars).fit()

Solution

  • As far as I know, that file chunk option comes with knitr render engine. But as you are using python code chunk, Quarto will try to render the qmd document with Jupyter. Hence file is not working and therefore, you are getting that NameError.

    You can try the following as a workaround where you need to use the quarto extension include-code-files to include code from an external script and use the %run jupyter line magic to evaluate codes from an external file.

    ---
    format: pdf
    execute:
      cache: false
    jupyter: python3
    filters: 
      - include-code-files
    ---
    
    ```{.python include="lm.py"}
    ```
    
    ```{python}
    #| echo: false
    %run lm.py
    ```
    
    ```{python}
    print(model.summary())
    ```
    

    include and run from external py file