How can I specify rmarkdown to use python3 instead python 2?

与世无争的帅哥 提交于 2021-01-27 02:54:59

问题


I am trying to run python as rmarkdwon code chunks. I was sucessfull but rmarkdown by default uses python2 and I want it to use python 3. I am running it on Ubuntu with python 2.7.6 installed and I installed anaconda with pytthon 3.5, which is the one I want rmarkdown use. Here is the code and output of the python chunk in rmarkdown

```{python}
import sys
print (sys.version)
```

and the output:

2.7.6 (default, Jun 22 2015, 17:58:13) 

Any ideas?


回答1:


You can add engine.path = '/path/to/python3' to override the python (2) executable. For example,

---
title: "python"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{python}
import sys
print(sys.version)
```

```{python, engine.path = '/usr/bin/python3'}
import sys
print(sys.version)
```




回答2:


You can select your desired python version, as default, with an R chunk:

```{r setup, echo=FALSE}
library(knitr)
opts_chunk$set(engine.path = '/usr/bin/python3')
```

From now on your python chunks will use Python3:

```{python}
import sys
print(sys.version)
```

This way to select python version avoids to add the engine.path variable to every code chunk.




回答3:


Actually, if you are running Python 3.x, which I am, I had to do the following (obviously your path to the Python3 executable might be different):

```{r Setup, echo=FALSE}
library(knitr)
opts_chunk$set('python', engine.path='/usr/local/Cellar/python3/3.6.3/bin/python3')

```

And could then create a chunk using just python and it would run in the correct version:

```{python, cache=TRUE, echo = FALSE, eval = TRUE}

import sys
print(sys.version)

```



回答4:


You can use the reticulate package and insert an R chunk at the beginning:

```{r}
library(reticulate)
use_python("/usr/local/bin/python3")
```


来源:https://stackoverflow.com/questions/39069158/how-can-i-specify-rmarkdown-to-use-python3-instead-python-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!