Run current Python chunk

After I discovered reticulate, I like to use RMarkdown to write my documents that has Python code. Everything works as expected when I need to convert my .Rmd file with Python code to a .html file. Unfortunately, I'm facing challenges during the process of writing the document and test Python code chunk. If I have the following .Rmd document

---
title: "Sample"
author: "Raniere Silva"
date: "30 January 2019"
output: html_document
---

```{python}
print(1 + 1)
```

```{python}
import pandas
print(pandas.__version__)
```

I can use the "Run Current Chunk" feature of RStudio without problem for the first chunk but not the second. The second chunk gives me

Traceback (most recent call last):
  File "/tmp/Rtmpa7PXBX/chunk-code4bf337ad4e99.", line 1, in <module>
    import pandas
ModuleNotFoundError: No module named 'pandas'

I have panda installed in the r-reticulate environment, the one used when converting from .Rmd to .html. Any work around?

If you have two versions of python in your system reticulate uses the default version (maybe 2.7) and if pandas is not installed under that version you cant use it.
Try to explicitly specify your python engine, similar to this.

```{r setup}
library(reticulate)
use_python("/usr/bin/python3")
matplotlib <- import("matplotlib")
matplotlib$use("Agg", force = TRUE)
```

```{python, engine.path = '/usr/bin/python3'}
```
1 Like

Thanks @andresrcs for the reply. Explicitly specify the Python engine solve the problem for me. If I use

```{python, engine.path="/home/raniere/anaconda3/envs/r-reticulate/bin/python"}
import pandas
print(pandas.__version__)
```

I will get the version of pandas as expected. Write engine.path in all the code chunks is tedious. Do you have a solution for that? I tried

```{r setup}
library(reticulate)
use_python("/home/raniere/anaconda3/envs/r-reticulate/bin/python")
```

and

```{r}
knitr::opts_chunk$set(engine.path = list(
  python = "/home/raniere/anaconda3/envs/r-reticulate/bin/python"
))
```

but didn't work.

Those should work, try installing the development version of reticulate from GitHub

devtools::install_github("rstudio/reticulate")

Yes this should work. but you also need newer version of knitr and rmarkdown. Be sure to be up to date.

Interesting documentation is on the reticulate website.

I updated reticulate, knitr, rmarkdown and RStudio with devtools but the "Run current chunk" is not working without engine.path.

As showed in the screenshot, the .html generated by rmarkdown is fine.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.