编织时 Reticulate 无法访问 Python 中的 R 变量,除非 RStudio 中的 运行

Reticulate can't access R variables in Python when knitting unless running in RStudio

我有一个包含以下内容的 RMarkdown 文档:

```{r setup, include=FALSE}
library(reticulate)
```

```{r}
#These lines don't seem to make a difference, but I have seen them suggested elsewhere
reticulate::use_python('/usr/local/Cellar/python@3.8/3.8.6_2/bin/python3.8')
knitr::knit_engines$set(python = reticulate::eng_python)
```


```{r}
py <- reticulate::py
```


```{python}
import sys
sys.version

a = 1
```


```{r python from r}
print(py$a)
b <- 2
```

```{python r from python}
print(r.b)
```

如果我在 RStudio 中 运行 以交互方式或通过编织整个文档,一切正常,最后一个块打印“2”。但是,当通过 render(或我执行常规模型训练的生产脚本)从 R 控制台 运行ning 时,它在最后一个块上失败并出现以下错误:

Error in py_call_impl(callable, dots$args, dots$keywords) :
RuntimeError: Evaluation error: object 'b' not found.

Detailed traceback: File "", line 1, in File "/Library/Frameworks/R.framework/Versions/3.6/Resources/library/reticulate/python/rpytools/call.py", line 21, in python_function raise RuntimeError(res[kErrorKey])

从 R 访问 Python 变量似乎工作正常,但我无法访问 Python 中的 R 变量。

我正在使用 Reticulate 1.18、Knitr 1.30 和 rMarkdown 2.6。从 RStudio 和 R 控制台调用 py_config() returns 相同的结果:

>py_config()

python: /usr/local/Cellar/python@3.8/3.8.6_2/bin/python3.8 libpython:
/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/config-3.8-darwin/libpython3.8.dylib pythonhome:
/usr/local/Cellar/python@3.8/3.8.6_2/Frameworks/Python.framework/Versions/3.8:/usr/local/Cellar/python@3.8/3.8.6_2/Frameworks/Python.framework/Versions/3.8 version: 3.8.6 (default, Nov 20 2020, 18:29:40) [Clang 12.0.0 (clang-1200.0.32.27)] numpy:
/usr/local/lib/python3.8/site-packages/numpy numpy_version: 1.18.5

NOTE: Python version was forced by RETICULATE_PYTHON

看起来这在当前版本的 Reticulate 中已损坏。我降级到 1.16 并修复了它,1.17 及更高版本已损坏。我已经向开发者提交了一张票:https://github.com/rstudio/reticulate/issues/914

编辑:这在最新的开发版本中已经修复,可以使用 remotes::install_github("rstudio/reticulate")

安装

它发生在我身上是因为我有一个愚蠢的想法在 RMarkdown 脚本中命名一个对象 r

```{python}
import requests
r = requests.get('http://api.worldbank.org/v2/countries?incomeLevel=LMC')
r.content
```

将在 python 解释器中工作,但可能 return RMarkdown 文档中的错误(因为 reticulate 在 python 中查找对象 content环境)

最佳解决方法:在使用 reticulate

时从不命名对象 r